这个简单的代码段可以熟悉getX(),getRawX()等方法,实现按钮的拖动效果:
package com.example;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class ButtonDrag extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button btn = (Button) findViewById(R.id.btn_hello);
btn.setOnTouchListener(new OnTouchListener() {
int[] temp = new int[] { 0, 0 };
public boolean onTouch(View v, MotionEvent event) {
int eventaction = event.getAction();
int x = (int) event.getRawX();
int y = (int) event.getRawY();
switch (eventaction) {
case MotionEvent.ACTION_DOWN:
temp[0] = (int) event.getX();
temp[1] = (int) event.getY();
break;
case MotionEvent.ACTION_MOVE:
v.layout(x - temp[0], y - temp[1], x + v.getWidth()
- temp[0], y + v.getHeight() - temp[1]);
// run in non_UI thread
v.postInvalidate();
break;
case MotionEvent.ACTION_UP:
break;
}
return false;
}
});
}
}