androidandroid-recyclerviewontouchlistener

Highlight item in RecyclerView while Pressed


I can't seem to find a simpler way to only highlight a RecyclerView item when pressed but while this code I have come up with seems to work ok it will remove the highlight (ACTION_CANCEL occurs) if I move up/down (while pressed) but it stays highlighted if I move right or left while pressed (No ACTION_CANCEL event is called). Can anyone tell me why or if there is better way of doing this please?

           itemView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View view, MotionEvent pEvent) {
                selected_position = getAdapterPosition();
                if(pEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    parent.setBackgroundColor(Color.RED);
                    txtName.setTextColor(Color.GREEN);
                }
                else if(pEvent.getAction() == MotionEvent.ACTION_UP) {
                    parent.setBackgroundColor(Color.WHITE);
                    txtName.setTextColor(Color.BLACK);
                }
                else if(pEvent.getAction() == MotionEvent.ACTION_CANCEL) {
                    parent.setBackgroundColor(Color.WHITE);
                    txtName.setTextColor(Color.BLACK);
                }
                else if(pEvent.getAction() == MotionEvent.ACTION_MOVE) {
                    int x = (int)pEvent.getRawX();
                    int y = (int)pEvent.getRawY();
                    int[] coordinates = new int[2];
                    parent.getLocationInWindow(coordinates);
                    if(x < (coordinates[0]) || (x > (coordinates[0]) + parent.getWidth())) {
                        parent.setBackgroundColor(Color.WHITE);
                        txtName.setTextColor(Color.BLACK);
                    }
                    else if(y < (coordinates[1]) || (y > (coordinates[1]) + parent.getHeight())) {
                        parent.setBackgroundColor(Color.WHITE);
                        txtName.setTextColor(Color.BLACK);
                    }
                    else {
                        parent.setBackgroundColor(Color.RED);
                        txtName.setTextColor(Color.GREEN);
                    }
                }
                return false;
            }
        });

Solution

  • In the root layout of your recycler view item.xml, you can write android:foreground="?attr/selectableItemBackground". This will highlight recycler view item, when a click occurs.

    For example, let`s say it is your recycler view item layout:

     <androidx.constraintlayout.widget.ConstraintLayout
    
        android:id="@+id/item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:foreground="?attr/selectableItemBackground">
    
         ...
    
    </androidx.constraintlayout.widget.ConstraintLayout>`