触摸侦听器不起作用。我需要将图像拖到屏幕上并放到以前的位置。
为此,我编写如下代码:
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;
}
}
但它拖过屏幕而不是落在前一个位置。请给我任何帮助
答案 0 :(得分: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);
}
}