主要代码部分:
实现View的onTouch方法,变换落点的X,Y坐标,定义两个变量存放拖动前的坐标位置.
int prevX,prevY;
@Override
public boolean onTouch(final View v,final MotionEvent event)
{
final FrameLayout.LayoutParams par=(FrameLayout.LayoutParams)v.getLayoutParams();
switch(event.getAction())
{
case MotionEvent.ACTION_MOVE:
{
par.topMargin+=(int)event.getRawY()-prevY;
prevY=(int)event.getRawY();
par.leftMargin+=(int)event.getRawX()-prevX;
prevX=(int)event.getRawX();
v.setLayoutParams(par);
return true;
}
case MotionEvent.ACTION_UP:
{
par.topMargin+=(int)event.getRawY()-prevY;
par.leftMargin+=(int)event.getRawX()-prevX;
v.setLayoutParams(par);
return true;
}
case MotionEvent.ACTION_DOWN:
{
prevX=(int)event.getRawX();
prevY=(int)event.getRawY();
par.bottomMargin=-2*v.getHeight();
par.rightMargin=-2*v.getWidth();
v.setLayoutParams(par);
return true;
}
}
return false;
}
});
完整代码:
package com.light.dragdropview; import android.app.Activity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.FrameLayout; public class MainActivity extends Activity { public FrameLayout board; public View pawn; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); board = new FrameLayout(this); pawn = new View(this); setContentView(R.layout.activity_main); board = (FrameLayout) findViewById(R.id.Board); findViewById(R.id.Pawn).setOnTouchListener(new OnTouchListener() { int prevX,prevY; @Override public boolean onTouch(final View v,final MotionEvent event) { final FrameLayout.LayoutParams par=(FrameLayout.LayoutParams)v.getLayoutParams(); switch(event.getAction()) { case MotionEvent.ACTION_MOVE: { par.topMargin+=(int)event.getRawY()-prevY; prevY=(int)event.getRawY(); par.leftMargin+=(int)event.getRawX()-prevX; prevX=(int)event.getRawX(); v.setLayoutParams(par); return true; } case MotionEvent.ACTION_UP: { par.topMargin+=(int)event.getRawY()-prevY; par.leftMargin+=(int)event.getRawX()-prevX; v.setLayoutParams(par); return true; } case MotionEvent.ACTION_DOWN: { prevX=(int)event.getRawX(); prevY=(int)event.getRawY(); par.bottomMargin=-2*v.getHeight(); par.rightMargin=-2*v.getWidth(); v.setLayoutParams(par); return true; } } return false; } }); } }
布局XML:
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/Board" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="top" > <View android:id="@+id/Pawn" android:layout_width="40dp" android:layout_height="40dp" android:layout_gravity="top" android:background="@drawable/ic_launcher" > </View> </FrameLayout>