我设法做到了,我发现的唯一方法是使用 SimpleOnGestureListener。如果有人遇到同样的问题,我复制粘贴代码。
像这样创建一个类:
public abstract class MyGestureDetector extends SimpleOnGestureListener {
private static final int SWIPE_MIN_DISTANCE = 100;
private static final int SWIPE_THRESHOLD_VELOCITY = 50;
private GestureDetector gestureDetector;
private View.OnTouchListener gestureListener;
private Activity activity;
public MyGestureDetector(Activity activity) {
this.activity = activity;
gestureDetector = new GestureDetector(this);
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
};
}
public abstract void onRightToLeftSwipe();
public abstract void onLeftToRightSwipe();
public abstract void onTopToBottomSwipe();
public abstract void onBottomToTopSwipe();
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velX,
float velY) {
DisplayMetrics dm = activity.getResources().getDisplayMetrics();
int REL_SWIPE_MIN_DISTANCE = (int) (SWIPE_MIN_DISTANCE * dm.densityDpi / 160.0f);
int REL_SWIPE_THRESHOLD_VELOCITY = (int) (SWIPE_THRESHOLD_VELOCITY
* dm.densityDpi / 160.0f);
float deltaX = e1.getX() - e2.getX();
float deltaY = e1.getY() - e2.getY();
try {
// swipe horizontal?
if ((Math.abs(deltaX) > REL_SWIPE_MIN_DISTANCE)
&& (Math.abs(velX) > REL_SWIPE_THRESHOLD_VELOCITY)
&& (Math.abs(deltaX) > Math.abs(deltaY))) {
// left or right
if (deltaX < 0) {
this.onLeftToRightSwipe();
return true;
}
if (deltaX > 0) {
this.onRightToLeftSwipe();
return true;
}
} else if ((Math.abs(deltaY) > REL_SWIPE_MIN_DISTANCE)
&& (Math.abs(velY) > REL_SWIPE_THRESHOLD_VELOCITY)) { // swipe
// vertical
// top or down
if (deltaY < 0) {
this.onTopToBottomSwipe();
return true;
}
if (deltaY > 0) {
this.onBottomToTopSwipe();
return true;
}
} else {
return false; // We don't consume the event
}
} catch (Exception e) {
// nothing
}
return false;
}
public View.OnTouchListener getGestureListener() {
return gestureListener;
}
public void setGestureListener(View.OnTouchListener gestureListener) {
this.gestureListener = gestureListener;
}
}
那么你必须在你的活动中这样做:
public void onCreate(Bundle savedInstanceState) {
// Initializate your variables here
// Using Gestures
MyGestureDetector gestos = new MyGestureDetector(this) {
@Override
public void onTopToBottomSwipe() {
// Do whatever
}
@Override
public void onRightToLeftSwipe() {
// Do whatever
}
@Override
public void onLeftToRightSwipe() {
// Do whatever
}
@Override
public void onBottomToTopSwipe() {
// Do whatever
}
};
最后但并非最不重要的一点是,您必须将 TouchListener 放入您想要在其中滑动的布局以及该布局中的每个可点击的视图
layoutSwipe = (LinearLayout) findViewById(R.id.layoutSwipe);
layoutSwipe.setOnTouchListener(gestos.getGestureListener());
viewInsidells.setOnTouchListener(gestos.getGestureListener());
view2Insidells.setOnTouchListener(gestos.getGestureListener());
有了这个,你可以在你的布局中使你的视图可以点击,如果你点击它只会执行你点击的视图的点击动作,如果你滑动它只会根据你的动作执行滑动动作。
我花了 4 个小时试图解决这个问题,希望我可以为下一个节省一些时间。