我有一个Android应用程序,它是Web视图中的全部。当用户在应用程序的背景上滑动而不是滑块或按钮时,我想抓住。
我尝试将GestureDetector附加到WebView,但是它捕获了所有滑动,包括WebView中控件的滑动。我怎样才能抓住背景滑动?
答案 0 :(得分:0)
在阅读了许多答案之后,我终于想出了一个简单的解决方案。
1-为您的操作创建一个简单的界面:
public interface TouchListener {
default void onSwipeLeft() {
Logger.d( "Swipe left");
}
default void onSwipeRight() {
Logger.d( "Swipe right");
}
}
2-创建一个简单的OnTouchListener:
public class OnSwipeWebviewTouchListener implements View.OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeWebviewTouchListener(Context ctx, TouchListener touchListener) {
gestureDetector = new GestureDetector(ctx, new GestureListener(touchListener));
}
@Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends GestureDetector.SimpleOnGestureListener {
private TouchListener touchListener;
GestureListener(TouchListener touchListener) {
super();
this.touchListener = touchListener;
}
@Override
public boolean onDown(MotionEvent e) {
return false; // THIS does the trick
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
// You can customize these settings, so 30 is an example
if (Math.abs(diffX) > 30 && Math.abs(velocityX) > 30) {
if (diffX > 0) {
touchListener.onSwipeRight();
} else {
touchListener.onSwipeLeft();
}
result = true;
}
} else {
result = false;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
}
}
3-将它们简单地连接在一起:
webView.setOnTouchListener( new OnSwipeWebviewTouchListener( getActivity(), this));