How can I select only one checkbox in Recyclerview and notifydataset changed

前端 未结 5 1156
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 14:14

In my code I have create recyclerview with check box and default one item selected already. now I want when select other item checkbox so deselect all other items mean one i

5条回答
  •  清歌不尽
    2020-12-09 14:44

    1- You can create a variable inside Adapter class that can be used to hold the selected position:

    private int selectedPosition = -1;// no selection by default

    2- Inside onBindViewHolder set Check State:

    holder.checkBox.setChecked(selectedPosition == position);

    3- Inside setOnCheckedChangeListener you must update position

    this.selectedPosition = holder.getAdapterPosition();

    4- Refresh adapter

    adapter.notifyDatasetChanged();

    EDIT

    onBindViewHolder will be called for all positions,

    So method setChecked will called for all CheckBoxes, This method have a boolean input.

    In above example i write setChecked(selectedPosition == position). For more readable i can write:

    if(selectedPosition == position){ 
       holder.checkBox.setChecked(true);
    }
    else{
       holder.checkBox.setChecked(false) 
    }
    

提交回复
热议问题