Choice Mode in a RecyclerView?
Solution 1
There is no built-in support for a "choice mode" structure with RecyclerView
. Your options are to either roll it yourself or use a third-party library that offers it.
The DynamicRecyclerView library offers choice modes, but I have not tried it.
This sample app demonstrates implementing it yourself, in this case using the activated state to indicate which is the current choice. The overall pattern is:
Have your
RecyclerView.ViewHolder
detect a UI operation that indicates a choice (click on a row? click on aRadioButton
in the row? etc.).Keep track of the selection at the level of your
RecyclerView.Adapter
. In my case, aChoiceCapableAdapter
handles that, in conjunction with aSingleChoiceMode
class that implements aChoiceMode
strategy.When a choice is made, update the newly-chosen row to reflect the choice and update the previously-chosen row to reflect that it is no longer chosen.
findViewHolderForPosition()
onRecyclerView
can help here -- if you track theposition
of the last choice,findViewHolderForPosition()
can give you theViewHolder
for that choice, so you can "un-choose" it.Keep track of the choice across configuration changes, by putting it in the saved instance state of the activity or fragment that is managing the
RecyclerView
.
Solution 2
I've created a library for this kind of choice mode applied to the RecyclerView, maybe it can help:
Description
This library has been created to help the integration of a multi-choice selection to the RecyclerView
Implementation
The integration with Gradle is very easy, you just need the jcenter repository and the library:
repositories {
jcenter()
}
...
dependencies {
compile 'com.davidecirillo.multichoicerecyclerview:multichoicerecyclerview:1.0.1'
}
Main steps for usage
Add the MultiChoiceRecyclerView to your xml file
<com.davidecirillo.multichoicesample.MultiChoiceRecyclerView
android:id="@+id/multiChoiceRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Instanciate you object and connect the view
MultiChoiceRecyclerView mMultiChoiceRecyclerView = (MultiChoiceRecyclerView) findViewById(R.id.multiChoiceRecyclerView);
Extend you adapter to the MultiChoiceAdapter and add it to the RecyclerView as per normal usage
public class MyAdapter extends MultiChoiceAdapter<MyViewHolder> {
public MyAdapter(ArrayList<String> stringList, Context context) {
this.mList = stringList;
this.mContext = context;
}
...
}
MyAdapter myAdapter = new MyAdapter(mList, getApplicationContext());
mMultiChoiceRecyclerView.setAdapter(myAdapter);
For more information and customisations: https://github.com/dvdciri/MultiChoiceRecyclerView
Spike Flail
Updated on February 04, 2020Comments
-
Spike Flail over 4 years
I'm trying to figure out how to achieve the same effect of
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
in a RecyclerView implementation. Please help.