how to highlight the selected Item of Recycler View?

how to highlight the selected Item of Recycler View?

We can find several ways to highlight the selected Item of Recycler View.
In this case We can use SparseBooleanArray, SparseBooleanArrays map integers to booleans. Unlike a normal array of booleans there can be gaps in the indices. It is intended to be more memory efficient than using a HashMap to map Integers to Booleans, both because it avoids auto-boxing keys and values and its data structure doesn’t rely on an extra entry object for each mapping.

Complete Code in GitHub
Now in our Adapter We can see how to use SparseBooleanArray.
First step We create a selected background

Create a new Drawable resource file in your drawable directory with the following content:

selector_row.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Color when the row is selected -->
    <item android:drawable="@android:color/darker_gray" android:state_pressed="false" android:state_selected="true" />
    <!-- Standard background color -->
    <item android:drawable="@android:color/white" android:state_selected="false" />
</selector>

Now simply use this StateListDrawable as the background in the row-layout of your RecyclerView

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/selector_row">

    <!-- row content -->
</RelativeLayout>

Now as soon as the onClick() method in your adapter is called you simply need to do the following:

// myBackground is the RelativeLayout root of your row
myBackground.setSelected(true);
The rows’ background will have the color (in this case darker_gray) as long as you call myBackground.setSelected(false). Of course you should create a SparseBooleanArray for example in order to know which row is selected and which isn’t since the rows will be reused when scrolling.

Edit: Remember selected items
The idea behind the SparseBooleanArray is to remember the items which are selected. Following a sample on how to use it:


public class UpdateDataAdapter extends RecyclerView
        .Adapter<UpdateDataAdapter
        .DataObjectHolder> {

    private ArrayList<UpdateData> mDataset;
    private static Context mContext;
    private static int mPosition;
    private static SparseBooleanArray sSelectedItems;
    private static UpdateDataClickListener sClickListener;

    static class DataObjectHolder extends RecyclerView.ViewHolder
            implements View
            .OnClickListener {
        TextView mLabel;
        TextView mDateTime;
        LinearLayout mBackground;


        DataObjectHolder(View itemView) {
            super(itemView);
            mLabel = (TextView) itemView.findViewById(R.id.vertical_list_item_title);
            mDateTime = (TextView) itemView.findViewById(R.id.vertical_list_item_subtitle);
            mBackground = (LinearLayout) itemView.findViewById(R.id.vertical_list_item_background);
            itemView.setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {
            if (sSelectedItems.get(getAdapterPosition(), false)) {
                sSelectedItems.delete(getAdapterPosition());
                mBackground.setSelected(false);
                mLabel.setTextColor(ContextCompat.getColor(mContext, android.R.color.black));
            } else {    
            
                mLabel.setTextColor(ContextCompat.getColor(mContext, R.color.colorAccent));
                sSelectedItems.put(getAdapterPosition(), true);
                mBackground.setSelected(true);
            }
            sClickListener.onItemClick(getAdapterPosition());
        }
    }

    void setOnItemClickListener(UpdateDataClickListener clickListener) {
        sClickListener = clickListener;
    }

    UpdateDataAdapter(ArrayList<UpdateData> myDataset, Context context, int modo) {
        mDataset = myDataset;
        mContext = context;
        sSelectedItems = new SparseBooleanArray();
     }

    @Override
    public UpdateDataAdapter.DataObjectHolder onCreateViewHolder(ViewGroup parent,
                                                                 int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.vertical_list_item, parent, false);

        UpdateDataAdapter.DataObjectHolder dataObjectHolder = new UpdateDataAdapter.DataObjectHolder(view);
        return dataObjectHolder;
    }

    @Override
    public void onBindViewHolder(UpdateDataAdapter.DataObjectHolder holder, int position) {
        holder.mLabel.setText(mDataset.get(position).getmTitle());
        if (sSelectedItems.get(position)) {
            holder.mLabel.setTextColor(ContextCompat.getColor(mContext, R.color.colorAccent));
        } else {
            holder.mLabel.setTextColor(ContextCompat.getColor(mContext, android.R.color.black));
        }
        holder.mDateTime.setText(mDataset.get(position).getmSubTitle());
        holder.mBackground.setSelected(sSelectedItems.get(position, false));
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

    public void selected(int position) {
       
    }

    public void changeMode(int modo) {
      
    }

    interface UpdateDataClickListener {
        void onItemClick(int position);
    }

}

This is one way how to highlight the selected Item of Recycler View.

Complete Code in GitHub

Delete item recyclerView

Remove item recyclerView

Delete item recyclerView

When we delete a item in our recyclerView, first step is in our adapter We must to add this:

void deleteItem(int index) {
        mDataset.remove(index);
        notifyItemRemoved(index);
    }

And now our fragment or activity we call the method like this:

mAdapter.deleteItem(position);

The example is in GitHub

Hopefully this steps will help you removing items from a recycler view, please, drop us a comment if you have any problems with this code.

ListView inside ScrollView II

See only one item

You do not have to do anything special in layout.xml file nor handle anything on the parent ScrollView. You only have to handle the child ListView. You can also use this code to use any type of child view inside a ScrollView & perform Touch operations.

ScrollView inside ListView

Just add these lines of code in your java class :

listView.setOnTouchListener(new ListView.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // Disallow the touch request for parent scroll on touch of child view
                v.getParent().requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });

Download code