fmpsagara
fmpsagara

Reputation: 485

Disable items in RecyclerView android

My RecyclerView is a list with checkboxes and at the bottom of the page is a submit button. When I click on the button, the checkboxes should be disabled but the state of those boxes that are already checked should retain. And also, how to access the checkbox since it's in the RecyclerView.ViewHolder? Help please.

Upvotes: 5

Views: 9254

Answers (4)

Chittu
Chittu

Reputation: 21

Change the Recyclerview background colour is Gray. In Recyclerview disable only work when some action is performed. if try to disable no action is performed, You have NULL Pointer exception.

Upvotes: 2

You will need to get your item in the list you passed to the adapter. If it is a custom adapter you can make a method to return your list, and code will be:

mAdapter.getList().get(4).setEnabled(false); //or equivalent
mAdapter.notifyDataSetChanged(); //or mRecycler.getAdapter().notifyDataSetChanged()

Upvotes: 2

DeeV
DeeV

Reputation: 36035

It's much better to have this as an attribute to the item that you're modeling.

So if the model item will have an "enabled" state that you can change.

public class Model {

   private boolean isEnabled;
   private boolean isChecked;

   public void setEnabled(boolean enabled) { 
      isEnabled = enabled;
   }

   public void setChecked(boolean checked) {
      isChecked = checked;
   }

   public boolean isEnabled() {
      return isEnabled;
   }

   public boolean isChecked() {
      return isChecked;
   }
}

Then your ViewHolder will check this attribute every time you bind to it. Additionally, the ViewHolder itself will listen for changes to the checkbox on the View that it handles.

public class ModelViewHolder extends RecyclerView.ViewHolder implements CompoundButton.OnCheckChangeListener {
   private CheckBox checkBox;
   private Model boundItem;

   public ModelViewHolder(View itemView) {
       checkBox = (CheckBox) itemView.findItemById(R.id.checkBoxId);
       checkBox.setOnCheckChangeListener(this);
   }

   public void bind(Model model) {
       boundItem = model;
       getItemView().setEnabled(model.isEnabled());
       checkBox.setChecked(model.isChecked());
   }

   @Override
   public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
       boundItem.setChecked(isChecked);
   }
}

Now, what this allows is the state of the item will be consistent while the user scrolls (since Views in RecyclerItem are re-used). It also allows you to use notifyItemChanged(int position) more easily on the item whenever you enable/disable the Model item.

Upvotes: 3

Konstantinos Michael
Konstantinos Michael

Reputation: 391

You can try that:

   RecyclerView rv=new RecyclerView(context);
   rv.getChildAt(5).setEnabled(false); // disables the 6th element

Upvotes: -3

Related Questions