【发布时间】:2014-11-19 16:44:12
【问题描述】:
我正在尝试使用触摸侦听器在 android 中向上滑动布局。当用户触摸屏幕并将手指向上拖动屏幕时,我期望 MOTION_UP 应该被拦截。而 MOTION_DOWN 则相反。但是当我调试时,Up 和 Down 都会被调用。
当我使用动画向上拖动时,我试图向上滑动布局。我不明白我做错了什么。以前有人遇到过这种情况吗?任何提示都有帮助,谢谢。
这是我的代码:
@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);
}
}
【问题讨论】:
标签: android ontouchlistener touch-event