Sun Sep 30 12:02:42 PDT 2018


Good morning to all, Those who all tried RecyclerView adapter with CheckBox, you all may find the issue on dynamic data change in RecyclerView. This will help you to resolve the issue in very simple way.




Video output of this project




So how to achieve this task effectively?



Simple, I hope you all tried with list objects only. Surely this object will have the boolean variable to know whether this object is selected or not. So now while we are select one object with the help of recyclerview and scroll down and up recyclerview adapter, the checked checkbox's position may change, this reflects on our object also, So how to avaid this issue.



simple, In our recyclerview adapter's
onBindViewHolder method, first set the checkedOnChangeListener of checkbox to null, and then set whether this object is selected or not to checkbox, and then add the checkedOnChangeListener to the checkbox. That's all. Issue solved.




onBindViewHolder
will be look like


    @Override
public void onBindViewHolder(final ViewHolder holder, int position) {

//in some cases, it will prevent unwanted situations
holder.checkbox.setOnCheckedChangeListener(null);

//if true, your checkbox will be selected, else unselected
holder.checkbox.setChecked(numbers.get(position).isSelected());

holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
numbers.get(holder.getAdapterPosition()).setSelected(isChecked);
}
});
}
here
numbers
is list of objects.



I hope this post is useful to you. kindly share your feedback as comment here.





Simple RecyclerView example in Android

Simple RecyclerView example with filter option in Android

Dynamically change ListView to GridView and Vice Versa using RecyclerView

Source code on GitHub









Thank You







Comments

Popular posts from this blog

termux vnc viewer setup

../Settings.jpg

me.html