回收视图中的单个选择

我知道在 RecyclerView类中没有默认的选择方法,但是我尝试了以下方法:

public void onBindViewHolder(ViewHolder holder, final int position) {
holder.mTextView.setText(fonts.get(position).getName());
holder.checkBox.setChecked(fonts.get(position).isSelected());


holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
for (int i = 0; i < fonts.size(); i++) {
fonts.get(i).setSelected(false);
}
fonts.get(position).setSelected(isChecked);
}
}
});
}

在尝试这段代码时,我得到了预期的输出,但并非完全如此。

我会用图片来解释。

默认情况下,从适配器中选择第一项。

然后我选择第二个,然后第三个,然后第四个,最后第五个。

这里只有第五个应该被选中,但是所有五个都被选中了。

如果我将列表滚动到底部,然后再次回到顶部,就会得到我所期望的结果。

我怎样才能克服这个问题?有时候,如果我快速滚动列表,其他一些项目会被选中。我怎样才能克服这个问题呢?

当我尝试在 fonts.get(position).setSelected(isChecked);之后使用 notifyDataSetChanged()时,我得到了下面的例外:

java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling
at android.support.v7.widget.RecyclerView.assertNotInLayoutOrScroll(RecyclerView.java:1462)
at android.support.v7.widget.RecyclerView$RecyclerViewDataObserver.onChanged(RecyclerView.java:2982)
at android.support.v7.widget.RecyclerView$AdapterDataObservable.notifyChanged(RecyclerView.java:7493)
at android.support.v7.widget.RecyclerView$Adapter.notifyDataSetChanged(RecyclerView.java:4338)
at com.app.myapp.screens.RecycleAdapter.onRowSelect(RecycleAdapter.java:111)
143771 次浏览

It looks like there are two things at play here:

(1) The views are reused, so the old listener is still present.

(2) You are changing the data without notifying the adapter of the change.

I will address each separately.

(1) View reuse

Basically, in onBindViewHolder you are given an already initialized ViewHolder, which already contains a view. That ViewHolder may or may not have been previously bound to some data!

Note this bit of code right here:

holder.checkBox.setChecked(fonts.get(position).isSelected());

If the holder has been previously bound, then the checkbox already has a listener for when the checked state changes! That listener is being triggered at this point, which is what was causing your IllegalStateException.

An easy solution would be to remove the listener before calling setChecked. An elegant solution would require more knowledge of your views - I encourage you to look for a nicer way of handling this.

(2) Notify the adapter when data changes

The listener in your code is changing the state of the data without notifying the adapter of any subsequent changes. I don't know how your views are working so this may or may not be an issue. Typically when the state of your data changes, you need to let the adapter know about it.

RecyclerView.Adapter has many options to choose from, including notifyItemChanged, which tells it that a particular item has changed state. This might be good for your use:

if(isChecked) {
for (int i = 0; i < fonts.size(); i++) {
if (i == position) continue;
Font f = fonts.get(i);
if (f.isSelected()) {
f.setSelected(false);
notifyItemChanged(i); // Tell the adapter this item is updated
}
}
fonts.get(position).setSelected(isChecked);
notifyItemChanged(position);
}

The solution for the issue:

public class yourRecyclerViewAdapter extends RecyclerView.Adapter<yourRecyclerViewAdapter.yourViewHolder> {


private static CheckBox lastChecked = null;
private static int lastCheckedPos = 0;




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

holder.mTextView.setText(fonts.get(position).getName());
holder.checkBox.setChecked(fonts.get(position).isSelected());
holder.checkBox.setTag(new Integer(position));


//for default check in first item
if(position == 0 && fonts.get(0).isSelected() && holder.checkBox.isChecked())
{
lastChecked = holder.checkBox;
lastCheckedPos = 0;
}
           

holder.checkBox.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
CheckBox cb = (CheckBox)v;
int clickedPos = ((Integer)cb.getTag()).intValue();


if(cb.isChecked())
{
if(lastChecked != null)
{
lastChecked.setChecked(false);
fonts.get(lastCheckedPos).setSelected(false);
}
                 

lastChecked = cb;
lastCheckedPos = clickedPos;
}
else
lastChecked = null;


fonts.get(clickedPos).setSelected(cb.isChecked);
}
});
}
}

Default value:

 private int mCheckedPostion = -1;

Just use mCheckedPosition to save the status:

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


holder.checkBox.setChecked(position == mCheckedPostion);
holder.checkBox.setOnClickListener(v -> {
if (position == mCheckedPostion) {
holder.checkBox.setChecked(false);
mCheckedPostion = -1;
}
else {
mCheckedPostion = position;
notifyDataSetChanged();
}
});
}

It's quite late, but I'm still posting it as it may help someone else.

Use the code below as a reference to check a single item in RecyclerView:

/**
* Created by subrahmanyam on 28-01-2016, 04:02 PM.
*/
public class SampleAdapter extends RecyclerView.Adapter<SampleAdapter.ViewHolder> {


private final String[] list;
private int lastCheckedPosition = -1;


public SampleAdapter(String[] list) {
this.list = list;
}


@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = View.inflate(parent.getContext(), R.layout.sample_layout, null);
ViewHolder holder = new ViewHolder(view);
return holder;
}


@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.choiceName.setText(list[position]);
holder.radioButton.setChecked(position == lastCheckedPosition);
}


@Override
public int getItemCount() {
return list.length;
}


public class ViewHolder extends RecyclerView.ViewHolder {
@Bind(R.id.choice_name)
TextView choiceName;
@Bind(R.id.choice_select)
RadioButton radioButton;


public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
radioButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int copyOfLastCheckedPosition = lastCheckedPosition;
lastCheckedPosition = getAdapterPosition();
notifyItemChanged(copyOfLastCheckedPosition);
notifyItemChanged(lastCheckedPosition);


}
});
}
}
}

This might help for those who want a single radiobutton to work --> Radio Button RecycleView - Gist

If lambda expressions aren't supported, use this instead:

View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
notifyItemChanged(mSelectedItem); // to update last selected item.
mSelectedItem = getAdapterPosition();
}
};

The following might be helpful for RecyclerView with Single Choice.

Three steps to do that, 1) Declare a global integer variable,

private int mSelectedItem = -1;

2) in onBindViewHolder

 mRadio.setChecked(position == mSelectedItem);

3) in onClickListener

mSelectedItem = getAdapterPosition();
notifyItemRangeChanged(0, mSingleCheckList.size());
mAdapter.onItemHolderClick(SingleCheckViewHolder.this);

This happens because RecyclerView, as the name suggests, does a good job at recycling its ViewHolders. This means that every ViewHolder, when it goes out of sight (actually, it takes a little more than going out of sight, but it makes sense to simplify it that way), it is recycled; this implies that the RecyclerView takes this ViewHolder that is already inflated and replaces its elements with the elements of another item in your data set.

Now, what is going on here is that once you scroll down and your first, selected, ViewHolders go out of sight, they are being recycled and used for other positions of your data set. Once you go up again, the ViewHolders that were bound to the first 5 items are not necessarely the same, now.

This is why you should keep an internal variable in your adapter that remembers the selection state of each item. This way, in the onBindViewHolder method, you can know if the item whose ViewHolder is currently being bound was selected or not, and modify a View accordingly, in this case your RadioButton's state (though I would suggest to use a CheckBox if you plan on selecting multiple items).

If you want to learn more about RecyclerView and its inner workings, I invite you to check FancyAdapters, a project I started on GitHub. It is a collection of adapters that implement selection, drag&drop of elements and swipe to dismiss capabilities. Maybe by checking the code you can obtain a good understanding on how RecyclerView works.

This simple one worked for me

private RadioButton lastCheckedRB = null;
...
@Override
public void onBindViewHolder(final CoachListViewHolder holder, final int position) {
holder.priceRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton checked_rb = (RadioButton) group.findViewById(checkedId);
if (lastCheckedRB != null && lastCheckedRB != checked_rb) {
lastCheckedRB.setChecked(false);
}
//store the clicked radiobutton
lastCheckedRB = checked_rb;
}
});

You need to clear the OnCheckedChangeListener before setting setChecked():

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


holder.mRadioButton.setOnCheckedChangeListener(null);
holder.mRadioButton.setChecked(position == mCheckedPosition);
holder.mRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {


mCheckedPosition = position;
notifyDataSetChanged();
}
});
}

This way it won't trigger the java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling error.

Please try this...

This works for me...

In the adapter, take a sparse Boolean array.

SparseBooleanArray sparseBooleanArray;

In the constructor, initialise this,

   sparseBooleanArray = new SparseBooleanArray();

In the bind holder, add:

@Override
public void onBindViewHolder(DispositionViewHolder holder, final int position) {
holder.tv_disposition.setText(dispList.get(position).getName());
if(sparseBooleanArray.get(position,false))
{
holder.rd_disp.setChecked(true);
}
else
{
holder.rd_disp.setChecked(false);




}
setClickListner(holder,position);
}


private void setClickListner(final DispositionViewHolder holder, final int position) {
holder.rd_disp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sparseBooleanArray.clear();
sparseBooleanArray.put(position, true);
notifyDataSetChanged();




}
});
}

rd_disp is a radio button in the XML file.

So when the recycler view loads the items, in the bindView Holder, it checks whether the sparseBooleanArray contains the value "true", corresponding to its position.

If the value returned is true then we set the radio button selection true. Else we set the selection false.

In onclickHolder I have cleared the sparseArray and set the value to true corresponding to that position.

When I call notify datasetChange, it again calls the onBindViewHolder and the conditions are checked again. This makes our selection to only select a particular radio.

            public class GetStudentAdapter extends
RecyclerView.Adapter<GetStudentAdapter.MyViewHolder> {


private List<GetStudentModel> getStudentList;
Context context;
RecyclerView recyclerView;


public class MyViewHolder extends RecyclerView.ViewHolder {
TextView textStudentName;
RadioButton rbSelect;


public MyViewHolder(View view) {
super(view);
textStudentName = (TextView) view.findViewById(R.id.textStudentName);
rbSelect = (RadioButton) view.findViewById(R.id.rbSelect);
}




}


public GetStudentAdapter(Context context, RecyclerView recyclerView, List<GetStudentModel> getStudentList) {
this.getStudentList = getStudentList;
this.recyclerView = recyclerView;
this.context = context;
}


@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.select_student_list_item, parent, false);
return new MyViewHolder(itemView);
}


@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.textStudentName.setText(getStudentList.get(position).getName());
holder.rbSelect.setChecked(getStudentList.get(position).isSelected());
holder.rbSelect.setTag(position); // This line is important.
holder.rbSelect.setOnClickListener(onStateChangedListener(holder.rbSelect, position));


}


@Override
public int getItemCount() {
return getStudentList.size();
}
private View.OnClickListener onStateChangedListener(final RadioButton checkBox, final int position) {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkBox.isChecked()) {
for (int i = 0; i < getStudentList.size(); i++) {


getStudentList.get(i).setSelected(false);


}
getStudentList.get(position).setSelected(checkBox.isChecked());


notifyDataSetChanged();
} else {


}


}
};
}


}

Here is a similar thing I have achieved.

The below code is from the application to select an address from a list of addresses that are displayed in cardview(cvAddress), so that on click of particular item(cardview) the imageView inside the item should set to a different resource (select/unselect):

    @Override
public void onBindViewHolder(final AddressHolder holder, final int position)
{
holderList.add(holder);
holder.tvAddress.setText(addresses.get(position).getAddress());
holder.cvAddress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
selectCurrItem(position);
}
});
}


private void selectCurrItem(int position)
{
int size = holderList.size();
for(int i = 0; i<size; i++)
{
if(i==position)
holderList.get(i).ivSelect.setImageResource(R.drawable.select);
else
holderList.get(i).ivSelect.setImageResource(R.drawable.unselect);
}
}

I don't know if this is the best solution or not, but this worked for me.

This is how it looks:

Single selection recyclerview best way

Inside your Adapter:

private int selectedPosition = -1;

And onBindViewHolder

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {


if (selectedPosition == position) {
holder.itemView.setSelected(true); //using selector drawable
holder.tvText.setTextColor(ContextCompat.getColor(holder.tvText.getContext(),R.color.white));
} else {
holder.itemView.setSelected(false);
holder.tvText.setTextColor(ContextCompat.getColor(holder.tvText.getContext(),R.color.black));
}


holder.itemView.setOnClickListener(v -> {
if (selectedPosition >= 0)
notifyItemChanged(selectedPosition);
selectedPosition = holder.getAdapterPosition();
notifyItemChanged(selectedPosition);
});
}

that’s it!

As you can see, I am just notifying (updating) the previous selected item and newly selected item.

My Drawable set it as a background for recyclerview child views:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="false" android:state_selected="true">
<shape android:shape="rectangle">
<solid android:color="@color/blue" />
</shape>
</item>

This is how the Adapter class looks like :

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewHolder>{


Context context;
ArrayList<RouteDetailsFromFirestore> routeDetailsFromFirestoreArrayList_;
public int  lastSelectedPosition=-1;




public MyRecyclerViewAdapter(Context context, ArrayList<RouteDetailsFromFirestore> routeDetailsFromFirestoreArrayList)
{
this.context = context;
this.routeDetailsFromFirestoreArrayList_ = routeDetailsFromFirestoreArrayList;
}


@NonNull
@Override
public MyRecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i)
{
// LayoutInflater layoutInflater = LayoutInflater.from(mainActivity_.getBaseContext());
LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
View view = layoutInflater.inflate(R.layout.route_details, viewGroup, false);
return new MyRecyclerViewHolder(view);
}


@Override
public void onBindViewHolder(@NonNull final MyRecyclerViewHolder myRecyclerViewHolder, final int i) {


/* This is the part where the appropriate checking and unchecking of radio button happens appropriately */
myRecyclerViewHolder.mRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b) {
if (lastSelectedPosition != -1) {
/* Getting the reference to the previously checked radio button and then unchecking it.lastSelectedPosition has the index of the previously selected radioButton */
//RadioButton rb = (RadioButton) ((MainActivity) context).linearLayoutManager.getChildAt(lastSelectedPosition).findViewById(R.id.rbRadioButton);
RadioButton rb = (RadioButton) ((MainActivity) myRecyclerViewHolder.mRadioButton.getContext()).linearLayoutManager.getChildAt(lastSelectedPosition).findViewById(R.id.rbRadioButton);
rb.setChecked(false);
}
lastSelectedPosition = i;
/* Checking the currently selected radio button */
myRecyclerViewHolder.mRadioButton.setChecked(true);
}
}
});
}


@Override
public int getItemCount() {
return routeDetailsFromFirestoreArrayList_.size();
}
} // End of Adapter Class

Inside MainActivity.java we call the ctor of Adapter class like this. The context passed is of MainActivity to the Adapter ctor :

myRecyclerViewAdapter = new MyRecyclerViewAdapter(MainActivity.this, routeDetailsList);

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);
    
  9. Notify this change by calling: adapter.notifyDataSetChanged(); immediately after this.

  10. 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);
    }
    

Don't make it too complicated:

SharedPreferences sharedPreferences = getSharedPreferences("appdetails", MODE_PRIVATE);


String selection = sharedPreferences.getString("selection", null);


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


String name = fonts.get(position).getName();


holder.mTextView.setText(name);


if(selection.equals(name)) {
holder.checkBox.setChecked(false);  //
holder.checkBox.setChecked(true);
}


holder.checkbox.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {


SharedPreferences sharedPreferences = getSharedPreferences("appdetails", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("selection", name);
r.setChecked(false);
editor.apply();
holder.checkBox.setChecked(true);
}
});


}
public class LastTransactionAdapter extends RecyclerView.Adapter<LastTransactionAdapter.MyViewHolder> {


private Context context;
private List<PPCTransaction> ppcTransactionList;


private static int checkedPosition = -1;


public LastTransactionAdapter(Context context, List<PPCTransaction> ppcTransactionList) {
this.context = context;
this.ppcTransactionList = ppcTransactionList;
}


@NonNull
@Override
public LastTransactionAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.last_transaction_item, parent, false));
}


@Override
public void onBindViewHolder(@NonNull LastTransactionAdapter.MyViewHolder holder, int position) {
holder.setLastTransaction(ppcTransactionList.get(position), position);
}


@Override
public int getItemCount() {
return ppcTransactionList.size();
}


public class MyViewHolder extends RecyclerView.ViewHolder {
private LinearLayout linTransactionItem;
private RadioButton radioButton;
private TextView tvDate, tvMerchantName, tvAmount, tvStatus;


public MyViewHolder(@NonNull View itemView) {
super(itemView);


linTransactionItem = itemView.findViewById(R.id.linTransactionItem);


tvDate = itemView.findViewById(R.id.tvDate);
tvMerchantName = itemView.findViewById(R.id.tvMerchantName);
tvAmount = itemView.findViewById(R.id.tvAmount);
tvStatus = itemView.findViewById(R.id.tvStatus);


radioButton = itemView.findViewById(R.id.radioButton);
}


public void setLastTransaction(PPCTransaction ppcTransaction, int position) {
tvDate.setText(ppcTransaction.getmDate());
tvMerchantName.setText(ppcTransaction.getmMerchantName());
tvAmount.setText(ppcTransaction.getmAmount());
tvStatus.setText(ppcTransaction.getmStatus());


if (checkedPosition == -1) {
radioButton.setChecked(false);
} else {
if (checkedPosition == getAdapterPosition()) {
radioButton.setChecked(true);
} else {
radioButton.setChecked(false);
}
}


linTransactionItem.setOnClickListener(v -> {
radioButton.setChecked(true);
if (checkedPosition != getAdapterPosition()) {
notifyItemChanged(checkedPosition);
checkedPosition = getAdapterPosition();
}
});
}
}

I got a solution that will save your selection when you open a recycler list.

var mSelectedItem = -1


// store saved selection
fun setSelection(position: Int) {
mSelectedItem = position
}


override fun onBindViewHolder(holder: GroupHolder, position: Int) {
holder.bind(dataList[position])
holder.radioButton.isChecked = position == mSelectedItem
}


inner class GroupHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val radioButton: RadioButton = itemView.rbValue
fun bind(data: Data) = with(itemView) {
radioButton.text = data.name


val clickListener = View.OnClickListener {
mSelectedItem = bindingAdapterPosition
notifyDataSetChanged()
setSelection(mSelectedItem)
}
radioButton.setOnClickListener(clickListener)
}
}

// This work for my with out any visual isue

data class buttonData(val button:RadioButton, val position: Int)

var selectedPosition = -1

override fun onBindViewHolder(holder: SingleChoiceAdapter.OptionHolder, position: Int) {
holder.viewDataBinding.option= options[position]
holder.viewDataBinding.radioButton.setChecked(position == selectedPosition);
buttonList.add( buttonData(holder.viewDataBinding.radioButton,position))


holder.viewDataBinding.radioButton.setOnClickListener {
selectedPosition=  position
for(buttonData in buttonList ){
buttonData.button.isChecked = buttonData.position == position
}
}
}