How to disable RecyclerView items in Android?

user6154174 picture user6154174 · Apr 5, 2016 · Viewed 9.3k times · Source

Textviews and Checkboxes are in a Recyclerview. Initially all Checkboxes are selected. I want to prevent user changing Checkboxes state but I do not want to prevent Recyclerview scroll. I would like to do this in my fragment class not in adapter class.

How can I prevent user changing Checkboxes state?

Below is the sample code written in onBindViewHolder in adapter class.

holder.cbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            //set your object's last status
            tblFilm.setSelected(isChecked);
        }
    });

The above code used for first mode which allows user clicks on checkbox.

After that I have second mode where I do not want to get clicked on checkbox at all.

For that I have done is below.

optionsoff(recyclerView);
private static void optionsOff(ViewGroup layout) {
        layout.setEnabled(false);
        layout.setClickable(false);
        for (int i = 0; i < layout.getChildCount(); i++) {
            View child = layout.getChildAt(i);
            if (child instanceof ViewGroup) {
                optionsOff((ViewGroup) child);
            } else {
                child.setEnabled(false);
                child.setClickable(false);
            }
        }

I guess this optionsoff() is not working. Because it is not disabling the checkbox. I can still click on checkbox. I need help on this second method which is disabling the Recyclerview items.

Answer

Anton Shkurenko picture Anton Shkurenko · Apr 5, 2016

Every CheckBox has method setEnabled.

In onBindViewHolder you can get the reference to the checkBox you want and disable it.

Something like this:

public void onBindViewHolder(ViewHolder holder, final int position) {
    holder.checkBox.setEnabled(data.get(position).isEnabled());
}

Also an answer below is working solution through the xml.