I am trying to slide up a layout in android using touch listener. I am expecting the MOTION_UP should be intercepted when the user touches the screen and drags the finger up the screen. And MOTION_DOWN the other way. But when i debug, both Up and Down are called.
I am trying to slide the layout up when I drag up using animation. I don't understand what i am doing wrong. Did anyone had this situation before? Any hints are helpful, Thank you.
This is my code:
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MainActivity extends Activity implements AnimationListener,
OnDragListener {
// Animation
private Animation animSlideUp;
private ImageView img;
private Rect rect;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView) findViewById(R.id.interstitialImg);
img.setOnDragListener(this);
img.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_UP) {
System.out.println("up");
rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v
.getBottom());
v.getHitRect(rect);
if (rect.contains(Math.round(v.getX() + event.getX()),
Math.round(v.getY() + event.getY()))) {
System.out.println("inside");
// Animation slide_up = AnimationUtils.loadAnimation(
// getApplicationContext(), R.anim.slide_up);
// img.startAnimation(slide_up);
} else {
// outside
System.out.println("outside");
}
}
if (event.getAction() == MotionEvent.ACTION_DOWN) {
System.out.println("down");
// Construct a rect of the view's bounds
rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v
.getBottom());
return true;
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
// if (!rect.contains(v.getLeft() + (int) event.getX(),
// v.getTop() + (int) event.getY())) {
// // User moved outside bounds
// System.out.println("moved outside bounds " + rect);
// }
}
return true;
}
});
}
@Override
public void onAnimationEnd(Animation animation) {
// check for zoom in animation
if (animation == animSlideUp) {
System.out.println("animation: " + animation);
overridePendingTransition(R.anim.slide_up, R.anim.slide_up);
finish();
}
}
@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
@SuppressLint("NewApi")
@Override
public boolean onDrag(View v, DragEvent e) {
if (e.getAction() == DragEvent.ACTION_DROP) {
System.out.println("action drop");
View view = (View) e.getLocalState();
ViewGroup from = (ViewGroup) view.getParent();
from.removeView(view);
RelativeLayout to = (RelativeLayout) v;
to.addView(view);
view.setVisibility(View.VISIBLE);
}
return true;
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.slide_up, R.anim.slide_up);
}
}