AndroidWorld

实现RecyclerView的OnItemClick的姿势

2017-05-27  本文已影响6人  mihope

RecyclerView只可以设置OnItemTouchListener,那么既然可以设置监听触摸事件,就可以从中解析获取点击、长按...事件了。

定义自己需要的回调接口

public interface RVItemClickListener {
    void onClick(View view, int position);

    void onLongClick(View view, int position);
}

重新实现自己的OnItemTouchListener

public class RVItemTouchListener implements RecyclerView.OnItemTouchListener {

    private GestureDetector gestureDetector;
    private RVItemClickListener clickListener;

    public RVItemTouchListener(Context context, final RecyclerView recyclerView, final RVItemClickListener clickListener) {
        this.clickListener = clickListener;
        gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {

            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                if (child != null && clickListener != null) {
                    clickListener.onLongClick(child, recyclerView.getChildLayoutPosition(child));
                }
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent e) {

        View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
        if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
            clickListener.onClick(child, recyclerView.getChildLayoutPosition(child));
        }
        return false;
    }

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

    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}

使用

        recyclerView.addOnItemTouchListener(new RVItemTouchListener(this, recyclerView, new RVItemClickListener() {
            @Override
            public void onClick(View view, int position) {

            }

            @Override
            public void onLongClick(View view, int position) {

            }
        }));
上一篇下一篇

猜你喜欢

热点阅读