当用户在屏幕的任何位置向右滑动时,我必须完成Activity
。我尝试使用GestureDetector
,如果Activity
中没有ScrollView
或RescyclerView
存在,并且具有onClickListener
的视图也不允许检测它们上面的滑动,则可以正常工作。因此,我采用了另一种方法,在程序中将一个视图覆盖到所有布局的顶部,然后尝试在其上检测滑动事件。
private void swipeOverToExit(ViewGroup rootView) {
OverlayLayout child = new OverlayLayout(this);
ViewGroup.LayoutParams layoutParams =
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
child.setLayoutParams(layoutParams);
rootView.addView(child);
}
OverlayLayout
public class OverlayLayout extends RelativeLayout {
private float x1, x2;
private final int MIN_DISTANCE = 150;
public OverlayLayout(Context context) {
super(context);
}
public OverlayLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public OverlayLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public OverlayLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
/*
* This method JUST determines whether we want to intercept the motion.
* If we return true, onTouchEvent will be called and we do the actual
* logic there.
*/
final int action = MotionEventCompat.getActionMasked(event);
Logger.logD("Intercept===", action + "");
// Always handle the case of the touch gesture being complete.
if (action == MotionEvent.ACTION_DOWN) {
return true; // Intercept touch event, let the parent handle swipe
}
Logger.logD("===", "Out side" + action + "");
// In general, we don't want to intercept touch events. They should be
// handled by the child view.
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x1 = event.getX();
break;
case MotionEvent.ACTION_UP:
x2 = event.getX();
float deltaX = x2 - x1;
if (Math.abs(deltaX) > MIN_DISTANCE) {
Logger.logD("Swipe Right===", MIN_DISTANCE + "");
return true;
} else {
Logger.logD("Tap===", "Tap===");
return super.onTouchEvent(event);
}
}
return true;
}
}
逻辑是如果在
OverlayLayout
上执行滑动操作,则拦截触摸事件到其他视图,然后结束Activity
。然而,现在我能够检测到在OverlayLayout
上的滑动事件,但即使我在onTouchEvent
的else条件中使用了return super.onTouchEvent(event);
,其他视图也无法响应,就像你在我的代码中看到的那样。请有人帮我解决这个问题。我被卡住了,非常想学习这个技巧 :)
return productGestureDetector.onTouchEvent(ev); } - Prashanth Debbadwar
touchIntercept
方法。 - Mohammed AtifdispatchTouchEvent
,但似乎没有帮助我解决问题。我尝试了所有的搜索,但都无法解决问题,所以最终来到这里向@Atif求助。如果您知道发生了什么,请给予帮助之手。谢谢。 - Stella