How To Select And Unselect The Recycleview In Android
I have created the recycleview.That recycleview contains checkbox.If i click the 1 st item in recycleview the checkbox is checked after that i click the 2nd item means the 1 st and
Solution 1:
Take one boolean in model class :
privateboolean isCheck;
publicbooleanisCheck() {
return isCheck;
}
publicvoidsetCheck(boolean check) {
isCheck = check;
}
In onBindViewHolder of Adapter :
private CompoundButton.OnCheckedChangeListenercheckedListener=newCompoundButton.OnCheckedChangeListener() {
@OverridepublicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stubintgetPosition= (Integer) v.getTag(); // Here we get the position that we have set for the checkbox using setTag.boolean flag= movieItems.get(getPosition).isCheck();
for (inti=0; i < movieItems.size(); i++) {
if (getPosition == i) {
movieItems.get(getPosition).setCheck(true);
} else {
movieItems.get(getPosition).setCheck(false);
}
}
notifyDataSetChanged();
// m.setSelected(isChecked);
});;
@OverridepublicvoidonBindViewHolder(final ViewHolder holder, finalint position) {
holder.checkbox.setOnCheckedChangeListener(null);
holder.checkbox.setChecked(movieItems.get(position).isCheck());
holder.checkbox.setOnCheckedChangeListener(checkedListener);
}
Solution 2:
Try this:
privateintlastSelectedPosition= -1; // adapter variable
holder.checkbox.setChecked(m.isSelected());
holder.checkbox.setOnCheckedChangeListener(newCompoundButton.OnCheckedChangeListener() {
@OverridepublicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {
intgetPosition= (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
movieItems.get(getPosition).setSelected(buttonView.isChecked());
final Child m=newChild();
if (getPosition != lastSelectedPosition) {
m.setSelected(isChecked);
if (lastSelectedPosition != -1) {
movieItems.get(lastSelectedPosition ).setSelected(false) // unselect last selection
notifyItemChanged(lastSelectedPosition); // notify adapter
}
}
lastSelectedPosition = isChecked ? getPosition : -1; // remember last selected position
}
});
holder.checkbox.setTag(position);
UPDATE
To avoid RecyclerView exception try to include notifyItemChanged call in an handler:
Handlerhandler=newHandler();
finalRunnabler=newRunnable() {
publicvoidrun() {
notifyItemChanged(lastSelectedPosition); // notify adapter
}
};
handler.post(r);
Post a Comment for "How To Select And Unselect The Recycleview In Android"