顾名思义,要实现控件的拖动效果就是,直白点说就是你拖着那控件到处跑. 这个功能应用前景那是刚刚的!
1/ 这里首先介绍并区别2种方法. getX() : 返回当前View的相对x点坐标.
getRawX() : 返回从屏幕原点计算的x点坐标.
2/ 自定义View. 为了直白,就一个Button. 当然也可以是其他的.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:id="@+id/btn_hello" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" />
</LinearLayout>
3/ Activity部分.
public class Touch 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(); // 得到事件动作
Log.i("&&&", "onTouchEvent:" + eventaction);
int x = (int) event.getRawX() ; // 记录下动作相对于原点的x坐标
int y = (int) event.getRawY(); // 记录下动作相对于原点的y坐标
switch (eventaction) {
case MotionEvent.ACTION_DOWN: // touch down so check if the
temp[0] = (int) event.getX() ;
temp[1] = y - v.getTop();
break;
case MotionEvent.ACTION_MOVE: // touch drag with the ball
v.layout(x - temp[0], y - temp[1], x + v.getWidth() - temp[0],
y - temp[1] + v.getHeight());
v.postInvalidate(); //redraw
break;
case MotionEvent.ACTION_UP:
break;
}
return false;
}
});
}
}