Skip to content

Instantly share code, notes, and snippets.

@guuilp
Last active January 6, 2019 17:43
Show Gist options
  • Save guuilp/1012b7f6ddaca26faf8c0907e9c0bf6c to your computer and use it in GitHub Desktop.
Save guuilp/1012b7f6ddaca26faf8c0907e9c0bf6c to your computer and use it in GitHub Desktop.
class PeopleAdapter(private val people: List<Person>, private val listener: Listener) :
RecyclerView.Adapter<PeopleAdapter.ViewHolder>() {
private var selectedPerson: Person? = null
interface Listener {
fun onItemClicked(person: Person)
}
fun updateSelectedPerson(person: Person) {
this.selectedPerson = person
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
ViewHolder(parent.inflate(R.layout.people_list_item))
override fun getItemCount() = people.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) =
holder.bind(people[position], listener)
override fun getItemId(position: Int) = people[position].id
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(person: Person, listener: Listener) = with(itemView) {
name.text = person.name
country.text = person.country
radio.isChecked = person == selectedPerson
setOnClickListener { listener.onItemClicked(person) }
radio.setOnClickListener { listener.onItemClicked(person) }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment