public class MainActivity extends Activity {
private int screenWidth;
private int screenHeight;
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
iv.setOnTouchListener(movingEventListener);
DisplayMetrics dm = getResources().getDisplayMetrics();
screenWidth = dm.widthPixels;
screenHeight = dm.heightPixels - 50;
}
private OnTouchListener movingEventListener = new OnTouchListener() {
int lastX, lastY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
// 触控笔按下
case MotionEvent.ACTION_DOWN:
Toast.makeText(MainActivity.this, "ACTION_DOWN", 1).show();
Log.e("11111111111:", "ACTION_DOWN");
// 得到X坐标
lastX = (int) event.getRawX();
// 得到Y坐标
lastY = (int) event.getRawY();
break;
// 触控笔移动
case MotionEvent.ACTION_MOVE:
int dx = (int) event.getRawX() - lastX;
int dy = (int) event.getRawY() - lastY;
int left = v.getLeft() + dx;
int top = v.getTop() + dy;
int right = v.getRight() + dx;
int bottom = v.getBottom() + dy;
// 设置不能出界
if (left < 0) {
left = 0;
right = left + v.getWidth();
}
if (right > screenWidth) {
right = screenWidth;
left = right - v.getWidth();
}
if (top < 0) {
top = 0;
bottom = top + v.getHeight();
}
if (bottom > screenHeight) {
bottom = screenHeight;
top = bottom - v.getHeight();
}
v.layout(left, top, right, bottom);
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
Log.e("222222222:", "ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Toast.makeText(MainActivity.this, "ACTION_UP", 1).show();
Log.e("333333333333:", "ACTION_UP");
break;
}
return true;
}
};
}
可参考:http://blog.csdn.net/qqtubo/article/details/8657242