美文网首页
SimpleOnItemTouchListener

SimpleOnItemTouchListener

作者: 有点健忘 | 来源:发表于2018-08-02 13:47 被阅读74次

    设置recyclerviewitem的点击事件,想偷懒,就直接在onBindViewHolder里,获取itemview然后setonclicklistener就完事了。

    如果想优雅一点,就用下边这种
    给recyclerview添加一个touchlistener

    rv.addOnItemTouchListener(ItemTouchListenerRV(rv))
    

    简单的实现如下,不过这种设置完
    可能发现你给item设置了状态背景,可item的背景不会改变,
    其实很简单,在item的跟布局上加上如下属性即可android:clickable="true"

    import android.support.v7.widget.RecyclerView;
    import android.view.GestureDetector;
    import android.view.MotionEvent;
    import android.view.View;
    
    /**
     * Created by charlie.song on 2018/5/8.
     */
    
    public class RvItemTouchListener extends RecyclerView.SimpleOnItemTouchListener {
        GestureDetector gestureDetector;
        RecyclerView rv;
    
        public RvItemTouchListener(RecyclerView rv) {
            this.rv = rv;
            gestureDetector = new GestureDetector(rv.getContext(), gestureListener);
        }
    
        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
            return gestureDetector.onTouchEvent(e);
        }
    
        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {
            super.onTouchEvent(rv, e);
            gestureDetector.onTouchEvent(e);
        }
    
        private GestureDetector.SimpleOnGestureListener gestureListener = new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                View child = rv.findChildViewUnder(e.getX(), e.getY());
                if (child != null) {
                    int position = rv.getChildAdapterPosition(child);
                    if (listener != null) {
                        listener.singleTab(position, rv.getChildViewHolder(child));
                    }
                }
                return super.onSingleTapUp(e);
            }
    
            @Override
            public void onLongPress(MotionEvent e) {
                super.onLongPress(e);
            }
        };
        public RvItemClickListener listener;
    
        public interface RvItemClickListener {
             void singleTab(int position, RecyclerView.ViewHolder viewHolder);
             void longPress(int position);
        }
    }
    

    相关文章

      网友评论

          本文标题:SimpleOnItemTouchListener

          本文链接:https://www.haomeiwen.com/subject/uuujvftx.html