1.素材
res/drawable-hdpi/ 目录下放四个jpg文件
beijing1_b.jpg
beijing2_b.jpg
beijing3_b.jpg
beijing4_b.jpg
2.main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linear"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageButton android:layout_width="100dip"
android:layout_height="100dip"
android:src="@drawable/beijing1_b"/>
android:src="@drawable/beijing2_b"/>
android:src="@drawable/beijing3_b"/>
android:src="@drawable/beijing4_b"/>
</LinearLayout>
3.java
package com.zj;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class ImageViewMoveActivity extends Activity {
private int point1;
private int point2;
private int startX;
private int startY;
private int p=4;
private LinearLayout lLayout;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lLayout = (LinearLayout)findViewById(R.id.linear);
OnTouchListener touchListener = new OnTouchListener(){
public boolean onTouch(View v, MotionEvent event) {//定义OnTouchListener 用于监听所有动作 并注册LinearLayour的所有View 实现为:
int action = event.getAction();
int x = (int) event.getRawX();
int y = (int) event.getRawY();
switch(action){
case MotionEvent.ACTION_DOWN://鼠标按下 拖拉动作开始
point1 = v.getTop();
startX = (int)event.getX();
startY = y - v.getTop();
break;
case MotionEvent.ACTION_MOVE://鼠标移动 拖拉动作进行中
v.layout(x - startX, y - startY, x + v.getWidth()- startX, y - startY + v.getHeight());
v.bringToFront();
v.postInvalidate();
case MotionEvent.ACTION_UP://鼠标释放 拖拉动作结束
point2 = v.getTop();
int dest = getLocation(v);//计算插入位置 位于哪两个相邻View之间
lLayout.removeView(v);//remove ori view, and then add view here
lLayout.addView(v, dest);
}
return false;
};
for(int i=0;i<lLayout.getChildCount();i++){
ImageView iv = (ImageView)lLayout.getChildAt(i);//to listener all ImageView
if(iv !=null){
iv.setOnTouchListener(touchListener);
else {
//error, view is null!
//4. getLocation(View) 用于: 根据目标View 判断待插入的位置 即:哪2个相邻ImageView 之间 实现为:
public int getLocation(View v){
ImageView iv = (ImageView)lLayout.getChildAt(i);ImageView iv2 = (ImageView)lLayout.getChildAt(i+1);
if(iv.getTop()< v.getTop() && iv2.getTop() > v.getTop()){
//refer delta of point1 & point2
if(point1 < point2){//drag to bottom
return i+1;
else {//drag to up
//otherwise return last location
return lLayout.getChildCount()-1;