Android RecyclerView single-choice adapter

Bigyan Thapa
2 min readDec 6, 2019
Single-choice color selector

More often than not, we as android developers come across a requirement to display a list of objects and make that list selectable in a single choice mode. Over the time, several ways of implementations have been done. I wanted to share the approach that I took recently to achieve this functionality. This requires basic understanding of Kotlin, data binding and a bit of MVVM pattern.

The basic idea here is to keep track of the selected position in the adapter as observable value and right after this changes, call notifyItemChanged() for the oldPosition and the newPosition with will re-bind the user to the views that will in turn reverse the check-mark for the associated RadioButton. When the list item is clicked, it updates the selectedPosition to the position of the clicked list item.

User data class

data class User(val name: String, val address: String, val age:Int)

RecyclerView Adapter class

View List Item class

User Fragment class

The source of data is the ViewModel. The view model fetches the users using some repository in the background thread and exposes that as LiveData. The Fragment can initialize the view model and observe the live data exposed by the view model. When it receives the data, it sets that data to the adapter which then binds that data to the RecyclerView. This is a pretty basic version of the implementation. We can take this approach and expand into multiple dimensions to achieve various different behaviors.

Please provide comments if you have questions or feedback.
Thank you!

Originally published at https://dev.to on December 6, 2019.

--

--

Bigyan Thapa

Senior Mobile Engineer @ Sprout Social, Android Dev, Chicago, USA