I’m trying to do an app which user can move image… And when the user move it to a certain place, app should do something else… Kinda unlocking…
But the problem is when ACTION_UP statement doesn’t work… Any suggestions?
Here’s my codes:
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;
}
});
}
}
Seems like your implementation is not exactly what you are looking for, you should assign
offset_xandoffset_yvalues insideACTION_UPinstead ofACTION_DOWN. Right now it will work like if user started dragging from x(120 to 150) and y(200 to 230) and drop anywhere. Unlock intent will fire, but what you want is drag from anywhere and drop to x(120 to 150) and y(200 to 230).So write: