如何将两个onTouchListener设置为同一布局中的两个按钮

时间:2013-01-07 21:51:57

标签: android drag-and-drop ontouchlistener

我正在尝试制作拖放按钮,它们位于相同的xml中,我为它们创建了两个onTouchListener,它们可以拖放,但如果我移动其中一个,另一个也移动,可以有人告诉我怎么解决这个问题?这是我的代码:

    btn = (Button) findViewById(R.id.btn);
    btn.setDrawingCacheEnabled(true);
    btn.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View view, MotionEvent me) {
            if (me.getAction() == MotionEvent.ACTION_DOWN) {
                status = START_DRAGGING;
            }
            if (me.getAction() == MotionEvent.ACTION_UP) {
                status = STOP_DRAGGING;
                Log.i("Drag", "Stopped Dragging");
            } 
            else if (me.getAction() == MotionEvent.ACTION_MOVE) {
                if (status == START_DRAGGING) {
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                            LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
                    layoutParams.setMargins((int) me.getRawX() - 50,(int) me.getRawY() - 70, 0, 0);


                    layout.removeView(btn);
                    layout.addView(btn, layoutParams);
                    btn.invalidate();
                }
            }
            return false;
        }
    });

    btn1 = (Button) findViewById(R.id.btn1);
    btn1.setDrawingCacheEnabled(true);
    btn1.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View view1, MotionEvent me1) {
            if (me1.getAction() == MotionEvent.ACTION_DOWN) {
                status = START_DRAGGING;
            }
            if (me1.getAction() == MotionEvent.ACTION_UP) {
                status = STOP_DRAGGING;
                Log.i("Drag", "Stopped Dragging");
            } 
            else if (me1.getAction() == MotionEvent.ACTION_MOVE) {
                if (status == START_DRAGGING) {
                    LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(
                            LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
                    layoutParams1.setMargins((int) me1.getRawX() - 50,(int) me1.getRawY() - 70, 0, 0);


                    layout.removeView(btn1);
                    layout.addView(btn1, layoutParams1);
                    btn1.invalidate();
                }
            }
            return false;
        }
    }
    );

1 个答案:

答案 0 :(得分:0)

请勿使用LinearLayout

我会使用RelativeLayoutFrameLayout

另请参阅:http://developer.android.com/guide/topics/ui/declaring-layout.html