@@ -3,14 +3,17 @@ package com.filipkowicz.examples.ui.main
33import android.annotation.SuppressLint
44import android.view.LayoutInflater
55import android.view.ViewGroup
6- import android.widget.TextView
6+ import androidx.databinding.ViewDataBinding
77import androidx.recyclerview.widget.DiffUtil
88import androidx.recyclerview.widget.ListAdapter
99import androidx.recyclerview.widget.RecyclerView
10+ import com.filipkowicz.examples.BR
1011import com.filipkowicz.examples.R
12+ import com.filipkowicz.examples.databinding.HeaderLayoutBinding
13+ import com.filipkowicz.examples.databinding.ItemLayoutBinding
1114
1215class Adapter
13- : ListAdapter <ListItem , RecyclerView . ViewHolder >(object : DiffUtil .ItemCallback <ListItem >() {
16+ : ListAdapter <ListItem , DataBindingViewHolder >(object : DiffUtil .ItemCallback <ListItem >() {
1417 override fun areItemsTheSame (oldItem : ListItem , newItem : ListItem ): Boolean {
1518 return oldItem.itemType == newItem.itemType
1619 }
@@ -21,29 +24,30 @@ class Adapter
2124 }
2225}) {
2326
24- override fun onCreateViewHolder (parent : ViewGroup , viewType : Int ): RecyclerView . ViewHolder =
27+ override fun onCreateViewHolder (parent : ViewGroup , viewType : Int ): DataBindingViewHolder =
2528 when (viewType) {
26- R .layout.item_layout -> LayoutInflater .from(parent.context).inflate(
27- viewType,
28- parent,
29- false
30- )
31- R .layout.header_layout -> LayoutInflater .from(parent.context).inflate(
32- viewType,
33- parent,
34- false
35- )
29+ R .layout.item_layout -> HeaderLayoutBinding .inflate(LayoutInflater .from(parent.context), parent, false )
30+ R .layout.header_layout -> ItemLayoutBinding .inflate(LayoutInflater .from(parent.context), parent, false )
3631 else -> throw IllegalArgumentException (" no supported item id" )
3732 }.let {
38- object : RecyclerView . ViewHolder (it) {}
33+ DataBindingViewHolder (it)
3934 }
4035
4136
42- override fun onBindViewHolder (holder : RecyclerView . ViewHolder , position : Int ) {
43- ( holder.itemView as ? TextView )?.text = (getItem(position) as ? MainViewModel .Data )?.data
37+ override fun onBindViewHolder (holder : DataBindingViewHolder , position : Int ) {
38+ holder.bind (getItem(position) as MainViewModel .Data )
4439 }
4540
4641 override fun getItemViewType (position : Int ): Int {
4742 return getItem(position).itemType
4843 }
44+ }
45+
46+ class DataBindingViewHolder (private val binding : ViewDataBinding ) : RecyclerView.ViewHolder(binding.root) {
47+
48+ fun bind (item : MainViewModel .Data ) {
49+ binding.setVariable(BR .data, item.data)
50+ binding.executePendingBindings()
51+ }
52+
4953}
0 commit comments