我正在尝试用户可以移动图片的应用程序...当用户将其移动到某个地方时,应用程序应该执行其他操作...有点解锁...
但问题是当ACTION_UP语句不起作用时......有什么建议吗?
这是我的代码:
public class Main extends Activity {
private View selected_item = null;
private int offset_x = 0;
private int offset_y = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ViewGroup vg = (ViewGroup) findViewById(R.id.lout);
vg.setOnTouchListener(new View.OnTouchListener() {
@Override
@SuppressWarnings("deprecation")
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_MOVE:
int x = (int) event.getX() - offset_x;
int y = (int) event.getY() - offset_y;
int w = getWindowManager().getDefaultDisplay().getWidth() - 100;
int h = getWindowManager().getDefaultDisplay().getHeight() - 100;
if (x > w)
x = w;
if (y > h)
y = h;
AbsoluteLayout.LayoutParams lp = new AbsoluteLayout.LayoutParams(
new ViewGroup.MarginLayoutParams(
AbsoluteLayout.LayoutParams.WRAP_CONTENT,
AbsoluteLayout.LayoutParams.WRAP_CONTENT));
lp.x = x;
lp.y = y;
selected_item.setLayoutParams(lp);
break;
default:
break;
}
return true;
}
});
ImageView img = (ImageView) findViewById(R.id.imageView1);
img.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
offset_x = (int) event.getX();
offset_y = (int) event.getY();
selected_item = v;
break;
case MotionEvent.ACTION_UP:
if (offset_x < 150 && offset_x > 120 && offset_y < 230
&& offset_y > 200)
startActivity(new Intent(
"com.yahya.GeneralTraining.UNLOCKED"));
break;
default:
break;
}
return false;
}
});
}
}
答案 0 :(得分:7)
我认为您需要在imageView onTouch()回调中返回true
。出于某种原因,在ACTION_DOWN
之后返回false会导致您无法使用ACTION_UP
进行另一次通话。
答案 1 :(得分:2)
你的onTouch函数必须返回true。这样可以避免其他侦听器控制事件并弄乱您的应用程序。
答案 2 :(得分:1)
看起来您的实施并不完全符合您的要求,您应该在offset_x
而不是offset_y
内分配ACTION_UP
和ACTION_DOWN
值。现在,它将起作用,如果用户开始从x(120到150)和y(200到230)拖动并放在任何地方。解锁意图会触发,但你想要的是从任何地方拖动并下降到x(120到150)和y(200到230)。
所以写:
@Override
public boolean onTouch(View v, MotionEvent event) {
//Are you sure you want event.getActionMasked() ??
//I use event.getAction()
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//I don't believe you really need anything to do here
break;
case MotionEvent.ACTION_UP:
offset_x = (int) event.getX();
offset_y = (int) event.getY();
selected_item = v;
if (offset_x < 150 && offset_x > 120 && offset_y < 230 && offset_y > 200)
startActivity(new Intent("com.yahya.GeneralTraining.UNLOCKED"));
break;
default:
break;
}
return false;
}
});