0

触摸监听器不起作用。我需要将图像拖到屏幕上并放到上一个位置本身。

为此,我编写如下代码:

class Mylistener implements OnTouchListener{

        @Override
            public boolean onTouch(View v, MotionEvent event) {
             MarginLayoutParams marginParams = new MarginLayoutParams(v.getLayoutParams()); 
              layoutParams2 = (RelativeLayout.LayoutParams) v.getLayoutParams();


                //int left=0,top=0;
                switch(event.getActionMasked())
                {
                    case MotionEvent.ACTION_DOWN:
                         startx=(int) event.getRawX();
                         starty=(int) event.getRawY();
                         System.out.println("ACTION DOWN: "+startx+","+starty);
                        break; 
                    case MotionEvent.ACTION_MOVE:


                       int  left = (int) event.getRawX() - (v.getWidth() / 2);
                      int top = (int) event.getRawY() - (v.getHeight());
                     marginParams.setMargins(left, top, 0, 0);
                     RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
                     v.setLayoutParams(layoutParams); 

                        break;

                    case MotionEvent.ACTION_UP:

                         marginParams.setMargins(startx, starty, 0, 0);
                         layoutParams2 = new RelativeLayout.LayoutParams(marginParams);
                         System.out.println("ACTION UP: "+startx+","+starty);

                         v.setLayoutParams(layoutParams2); 
                    default:
                        break;
                }
                return true;
            }

    }

但它在屏幕上拖动而不是放在以前的位置。请给我任何帮助

4

1 回答 1

2

在 Ur ACTION_DOWN 事件中,将触摸到的 imageView 的坐标记录为

// Global Declarations
float v_origX,v_origY; // Used for original X and Y of ImageViews

case MotionEvent.ACTION_DOWN:
{
.....
v_origX=v.getX();
v_origY=v.getY();
}

然后在 ACTION_UP 事件中,

case MotionEvent.ACTION_UP:
{
if(condition_fulfilled)
{
 // do ur stuff
}
else
{
// set the imageView back to original position
v.setX(v_origX);
    v.setY(v_origY);
}

}
于 2013-09-19T10:22:04.897 回答