顧名思義,要實現控件的拖動效果就是,直白點說就是你拖着那控件到處跑. 這個功能應用前景那是剛剛的!
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;
}
});
}
}