RecyclerView监听器的自定义

RecyclerView这个控件,也算是万能类的,比起ListView来说的话,更加表明的低耦合的概念,但是尼玛的,没有监听器,要自己手动写,没办法只能自己动手了,看代码,需要别的监听方式的可以根据的需要来按照这个思路自定义

监听器代码:

public class RecyclerViewOnClickListener implements RecyclerView.OnItemTouchListener{
    private GestureDetector mGestureDetector;
    private OnItemClickListener onItemClickListener;
    //自定义接口,用来实现回调
    public static interface OnItemClickListener {
        void onItemClick(View view,int postion);
        void onItemLongClick(View view,int postion);
    }
    //构造方法
    public RecyclerViewOnClickListener(Context context, final RecyclerView recyclerView, final OnItemClickListener onItemClickListener){
        this.onItemClickListener=onItemClickListener;
        mGestureDetector=new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){//手势处理
            @Override
            public boolean onSingleTapUp(MotionEvent e) {//手抬起的时候,触发这个动作
                View childView=recyclerView.findChildViewUnder(e.getX(),e.getY());//得到触摸的子控件
                if (childView!=null&&onItemClickListener!=null){
                   onItemClickListener.onItemClick(childView,recyclerView.getChildLayoutPosition(childView));
                   return true;
                }
                return super.onSingleTapUp(e);
            }

            @Override
            public void onLongPress(MotionEvent e) {
                super.onLongPress(e);
                View childView=recyclerView.findChildViewUnder(e.getX(),e.getY());
                if (childView!=null&&onItemClickListener!=null){
                    onItemClickListener.onItemLongClick(childView,recyclerView.getChildAdapterPosition(childView));
                }
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
        //当触发触摸手势的时候,将这个事件拦截给mGestureDetector来处理
        if (mGestureDetector.onTouchEvent(e)){
            return true;
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {

    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}

在需要的地方添加监听器

RVId.addOnItemTouchListener(new RecyclerViewOnClickListener(this, RVId, new RecyclerViewOnClickListener.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int postion) {
            Log.i("TAG", "onItemClick: "+postion);
        
        }

        @Override
        public void onItemLongClick(View view, int postion) {

        }
    }));
}
可以根据自己的需要的参数,自定义接口参数,大概就这样,以后有别的需求我再来修改

你可能感兴趣的:(RecyclerView监听器的自定义)