How do I get the position selected in a RecyclerView?

前端 未结 13 2419
自闭症患者
自闭症患者 2020-11-27 04:40

I am experimenting with the support library\'s recyclerview and cards. I have a recyclerview of cards. Each card has an \'x\' icon at the top right corner to remove it:

相关标签:
13条回答
  • 2020-11-27 05:06

    1. Create class Name RecyclerTouchListener.java

    import android.content.Context;
    import android.support.v7.widget.RecyclerView;
    import android.view.GestureDetector;
    import android.view.MotionEvent;
    import android.view.View;
    
    public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener 
    {
    
    private GestureDetector gestureDetector;
    private ClickListener clickListener;
    
    public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener 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.getChildAdapterPosition(child));
                }
            }
        });
    }
    
    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
    
        View child = rv.findChildViewUnder(e.getX(), e.getY());
        if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
            clickListener.onClick(child, rv.getChildAdapterPosition(child));
        }
        return false;
    }
    
    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {
    }
    
    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
    
    }
    
    public interface ClickListener {
        void onClick(View view, int position);
    
        void onLongClick(View view, int position);
    }
    }
    

    2. Call RecyclerTouchListener

    recycleView.addOnItemTouchListener(new RecyclerTouchListener(this, recycleView, 
    new RecyclerTouchListener.ClickListener() {
        @Override
        public void onClick(View view, int position) {
            Toast.makeText(MainActivity.this,Integer.toString(position),Toast.LENGTH_SHORT).show();
        }
    
        @Override
        public void onLongClick(View view, int position) {
    
        }
    }));
    
    0 讨论(0)
提交回复
热议问题