Single selection in RecyclerView

后端 未结 15 1146
深忆病人
深忆病人 2020-11-22 15:15

I know there are no default selection methods in recyclerview class, But I have tried in following way,

public void onBindViewHolder(ViewHolder holder, final         


        
15条回答
  •  再見小時候
    2020-11-22 15:55

    So, after spending so many days over this, this is what I came up with which worked for me, and is good practice as well,

    1. Create an interface, name it some listener: SomeSelectedListener.
    2. Add a method which takes an integer:void onSelect(int position);
    3. Initialise the listener in the recycler adapter's constructor as : a) first declare globally as: private SomeSelectedListener listener b) then in constructor initialise as: this.listener = listener;
    4. Inside onClick() of checkbox inside onBindViewHolder(): update the method of the interface/listener by passing the position as: listener.onSelect(position)
    5. In the model, add a variable for deselect say, mSelectedConstant and initialise it there to 0. This represents the default state when nothing is selected.
    6. Add getter and setter for the mSelectedConstant in the same model.
    7. Now, go to your fragment/activity and implement the listener interface. Then override its method: onSelect(int position). Within this method, iterate through your list which you are passing to your adapter using a for loop and setSelectedConstant to 0 for all:

    code

    @Override
    public void onTicketSelect(int position) {
    for (ListType listName : list) {
        listName.setmSelectedConstant(0);
    }
    

    8. Outside this, make the selected position constant 1:

    code

    list.get(position).setmSelectedConstant(1);
    
    1. Notify this change by calling: adapter.notifyDataSetChanged(); immediately after this.
    2. Last step: go back to your adapter and update inside onBindViewHolder() after onClick() add the code to update the checkbox state,

    code

    if (listVarInAdapter.get(position).getmSelectedConstant() == 1) {
        holder.checkIcon.setChecked(true);
        selectedTicketType = dataSetList.get(position);} 
    else {
        commonHolder.checkCircularIcon.setChecked(false);
    }
    

提交回复
热议问题