Android recyclerview item onTouchListener

285 views Asked by At

I want to be able to receive touch events (down, move and maybe up) from my recyclerview items. Now it does not fire at all. Here is my code:

FragmentMain.java

     noteRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
        @Override
        public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {

            return false;
        }

        @Override
        public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
            if (e.getAction() == MotionEvent.ACTION_DOWN) {
                child1 = rv.findChildViewUnder(e.getX(), e.getY());
                Log.e("down", "aaa");
            } else if (e.getAction() == MotionEvent.ACTION_MOVE) {
                Log.e("move", "aaa");
            }
        }


        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }
    });

How to solve that?

1

There are 1 answers

0
Ravinder Singh On

You have to place touchlistener in your adapter class in the onBindViewHolder method like this:

     @Override
            public void onBindViewHolder(final ViewHolder holder, int position) {
    
                holder.itemView.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View view, MotionEvent motionEvent) {
                        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                            // place your code here
                            Toast.makeText(getApplicationContext(), "Action Down", Toast.LENGTH_SHORT).show();
                        }
                        if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
                           // place your code here
                            Toast.makeText(getApplicationContext(), "Action Move", Toast.LENGTH_SHORT).show();
                        }
                        return false;
                    }
                });
    
            }