0

I was trying to change the background color when selecting an item in a RecyclerView but since this is a fairly new feature there isn't any quick and easy answers out there. Selectors didn't work for me either.

List item xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list_item_bg"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

</android.support.constraint.ConstraintLayout>

Java code

public class ScheduleTabAdapter extends RecyclerView.Adapter<ScheduleTabAdapter.ScheduleViewHolder> {

 public class ScheduleViewHolder extends RecyclerView.ViewHolder {

            @Bind(R.id.list_item_bg) ConstraintLayout mCL_BG;

            private Context mContext;

        //This is used for setting onClick methods for each item
        public ScheduleViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            mContext = itemView.getContext();
        }

   }

build.gradle

 annotationProcessor 'com.jakewharton:butterknife:7.0.1'
 implementation 'com.jakewharton:butterknife:7.0.1'
Greg432
  • 530
  • 4
  • 25

2 Answers2

0

Update Follow this guide

https://stackoverflow.com/a/49704439/6147989

Old answer

Add this line of code to the ScheduleViewHolder(View itemView) method.

   itemView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {

                    if (event.getAction() == MotionEvent.ACTION_MOVE){
                        mCL_BG.setBackgroundColor(Color.GRAY);
                    } else {
                        mCL_BG.setBackgroundColor(Color.TRANSPARENT);
                    }
                    return false;
                }
            });

//interesting fact, this will not work unless you have a OnClickListener
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {


                }
            });
Greg432
  • 530
  • 4
  • 25
0

Add android:background="?android:attr/selectableItemBackground" to the parent element of the layout that your RecyclerView adapter inflates (i.e your Recycler item layout)

Use this link for detail explanation

MashukKhan
  • 1,946
  • 1
  • 27
  • 46