使用onTouchListener不会在最后位置丢弃

时间:2014-02-19 10:23:31

标签: android ontouchlistener

我试图学习拖放,从我完成这个演示。请告诉我这段代码有什么问题?按钮没有用我的指尖移动。它定位很远......

            public class Home extends Activity implements OnTouchListener {

            private final static int START_DRAGGING = 0;
            private final static int STOP_DRAGGING = 1;

            private Button btn;
            private FrameLayout layout;
            private int status;
            private LayoutParams params;

            private ImageView image;

            /** Called when the activity is first created. */
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                layout = (FrameLayout) findViewById(R.id.LinearLayout01);
                // layout.setOnTouchListener(this);

                btn = (Button) findViewById(R.id.btn);
                btn.setDrawingCacheEnabled(true);
                btn.setOnTouchListener(this);

                params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                        LayoutParams.WRAP_CONTENT);

            }

            @Override
            public boolean onTouch(View view, MotionEvent me) {
                if (me.getAction() == MotionEvent.ACTION_DOWN) {
                    status = START_DRAGGING;
                    //image = new ImageView(this);
                    //image.setImageBitmap(btn.getDrawingCache());
                    //layout.addView(btn, params);
                    btn.setVisibility(View.INVISIBLE);
                }
                if (me.getAction() == MotionEvent.ACTION_UP) {
                    status = STOP_DRAGGING;
                    //btn.setPadding((int) me.getRawX(), (int) me.getRawY(), 0, 0);
                    btn.setVisibility(View.VISIBLE);
                    Log.i("Drag", "Stopped Dragging");
                } else if (me.getAction() == MotionEvent.ACTION_MOVE) {
                    if (status == START_DRAGGING) {
                        btn.setVisibility(View.VISIBLE);
                        System.out.println("Dragging"+me.getRawX()+","+me.getRawY());

                        btn.setX(me.getRawX());
                        btn.setY(me.getRawY());
                        btn.invalidate();

                    }
                }
                return false;
            }
        }

谢谢......请尽快告诉我......

1 个答案:

答案 0 :(得分:0)

为了简化您的任务,在API级别11中将Drag and Drop子框架添加到Android框架中。它非常容易实现并且也很好地解释了。

Android drag and drop sub framework

Example of drag and drop (name = Add to Cart)