解决ScrollView嵌套RecyclerView(横向)或ListView(横向)时,横向滑动不顺畅的问题。

来源:互联网 发布:java安装时出现错误 编辑:程序博客网 时间:2024/04/29 03:24

代码简单,容易理解,里面有点注释,够看了,特别少的改动。

package com.laka.live.ui.widget;import android.content.Context;import android.support.annotation.Nullable;import android.support.v7.widget.RecyclerView;import android.util.AttributeSet;import android.view.MotionEvent;/** * Created by Lyf on 2017/8/3. * 解决ScrollView与RecyclerView横向滚动时的事件冲突 */public class ScrollRecyclerView extends RecyclerView {    public ScrollRecyclerView(Context context) {        super(context);    }    public ScrollRecyclerView(Context context, @Nullable AttributeSet attrs) {        super(context, attrs);    }    public ScrollRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {        super(context, attrs, defStyle);    }    private float lastX, lastY;    @Override    public boolean onInterceptTouchEvent(MotionEvent e) {        boolean intercept = super.onInterceptTouchEvent(e);        switch (e.getAction()) {            case MotionEvent.ACTION_DOWN:                lastX = e.getX();                lastY = e.getY();                break;            case MotionEvent.ACTION_MOVE:                // 只要横向大于竖向,就拦截掉事件。                float slopX = Math.abs(e.getX() - lastX);                float slopY = Math.abs(e.getY() - lastY);              //  Log.log("slopX=" + slopX + ", slopY="  + slopY);                if( slopX >= slopY){                    requestDisallowInterceptTouchEvent(true);                    intercept = true;                }                break;            case MotionEvent.ACTION_UP:                intercept = false;                break;        }       // Log.log("intercept"+e.getAction()+"=" + intercept);        return intercept;    }}

备注:如果是ListView,直接将上面的RecyclerView类换成ListView就行了。

阅读全文
0 0