有这样一个需求:RecyclerView嵌套WebView时,当WebView显示宽度超出手机屏幕宽度时,需要用手指左右滑动WebView,但是由于手指在滑动时很难保持水平滑动,于是WebView和RecyclerView发生了滑动冲突,当手指稍微偏离水平方向时,WebView的滑动便停止,RecyclerView开始滑动,这样的体验很不好。于是乎便有了这样的自定义WebView:
public class RecyclerViewFitWebView extends WebView {
public float oldY;
public float oldX;
public float newY;
public float newX;
public RecyclerViewFitWebView(Context context) {
super(context);
}
public RecyclerViewFitWebView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
getParent().getParent().requestDisallowInterceptTouchEvent(true);
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
newX = ev.getX();
newY = ev.getY();
break;
case MotionEvent.ACTION_MOVE:
//手指滑动同时判断滑动方向,一旦滑动方向大于+-60便调用
//getParent().getParent().requestDisallowInterceptTouchEvent(false);
//将滑动事件交给RecyclerView来处理
oldX = newX;
oldY = newY;
newX = ev.getX();
newY = ev.getY();
float moveX = Math.abs(oldX - newX);
float moveY = Math.abs(oldY - newY);
//moveX * 1.73 < moveY ,判断左右滑动范围为+-60度
if (moveX * 1.73 < moveY) {
getParent().getParent().requestDisallowInterceptTouchEvent(false);
}
break;
}
return super.onTouchEvent(ev);
}
}
网友评论