`

android 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>

Touch.java
    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() ;
                    int y = (int) event.getRawY();

                    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;
                }
            });
        }
    }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics