android GestureDetector 基于webview的手势滑动实现
16lz
2021-01-23
Step 1: 初始化手势组件
detector = new GestureDetector(this, onGestureListener);
Step 2: 手势组件添加监听,为了方便各处使用,因此将监听事件独立出来了,用到的地方只需重写一下抽象方法即可
package com.example.demo.weimuyundemo.plugins.gesturedetector;import android.view.GestureDetector;import android.view.MotionEvent;public abstract class CustomGestureDetectorListener implements GestureDetector.OnGestureListener { @Override public boolean onDown(MotionEvent e) { return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } @Override public void onLongPress(MotionEvent e) { } @Override public abstract boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY);}
Step 3: 为webView添加touch监听
x5WebView.setOnTouchListener(this);
Step 4: 重写activity onTouch方法,绑定手势onTouch事件
@Override public boolean onTouch(View v, MotionEvent event) { return detector.onTouchEvent(event); }
Step 5: 重写手势监听的抽象方法,待Step 1使用
private CustomGestureDetectorListener onGestureListener = new CustomGestureDetectorListener() { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { float x = e2.getX() - e1.getX(); float y = e2.getY() - e1.getY(); judgeSwiperDirection(x,y); return true; } };/** * 判断左滑右滑 * @param xAxis X轴滑动距离 * @param yAxis Y轴滑动距离 */ private void judgeSwiperDirection (float xAxis, float yAxis) { boolean isYInControlled = Math.abs(yAxis) <= 100; if (isYInControlled) { if (xAxis > 25) { Log.i("TAG", "右滑触发"); if (null != x5WebView && x5WebView.canGoForward()) { x5WebView.goForward(); } } else if (xAxis < -25) { Log.i("TAG", "左滑触发"); if (null != x5WebView && x5WebView.canGoBack()) { x5WebView.goBack(); } else { Log.i("TAG", "手势返回到主页面"); Intent intent = new Intent(this, MainActivity.class); startActivity(intent); this.finish(); } } } }
Tip:
说明下,写这篇文章的时候是根据实际的业务需要些的,文章中是要给webview添加左滑右滑的,使用的是腾讯X5内核。因为只考虑左滑右滑,因此当上下滑动距离超过100的时候,就过滤掉了。
更多相关文章
- Android 自定义View之手势解锁控件
- Android 手势识别判断,GestureDetector封装
- 重写EditText回车键跳到下一个EditText
- 【Android每周专题】触摸屏手势
- Android:解决RadioGroup中RadioButton的图片自定义及每项间隔距离
- android线性布局控件之间的距离设置
- Android Gesture 手势识别使用实例 - Android - mobile - ITeye
- ASP.NET MVC重写的实例教程
- C#如何计算传入的时间距离今天的时间差的实例分享