SHARE
TWEET

Untitled

a guest Aug 25th, 2019 90 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import android.view.LayoutInflater
  2. import android.view.ViewGroup
  3. import androidx.databinding.DataBindingUtil
  4. import androidx.databinding.ViewDataBinding
  5. import androidx.recyclerview.widget.RecyclerView
  6.  
  7. /**
  8. * NB : Used in RS
  9. */
  10. open class AnyViewModelAdapter<MODEL, BINDING : ViewDataBinding>(
  11.     val layoutId: Int,
  12.     val items: MutableList<MODEL>,
  13.     val clickHandler: ((data: MODEL) -> Unit)? = null
  14. ) : RecyclerView.Adapter<AnyViewModelHolder<MODEL, BINDING>>() {
  15.  
  16.     constructor(layoutId: Int, clickHandler: ((data: MODEL) -> Unit)?) : this(layoutId, mutableListOf(), clickHandler)
  17.     constructor(layoutId: Int) : this(layoutId, mutableListOf(), null)
  18.  
  19.     protected lateinit var binding: BINDING
  20.  
  21.     open fun onBindedViewHolder(holder: AnyViewModelHolder<MODEL, BINDING>, data: MODEL) {}
  22.  
  23.     override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AnyViewModelHolder<MODEL, BINDING> {
  24.         return AnyViewModelHolder(
  25.             DataBindingUtil.inflate(
  26.                 LayoutInflater.from(parent.context),
  27.                 layoutId,
  28.                 parent,
  29.                 false
  30.             )
  31.         )
  32.     }
  33.  
  34.     override fun getItemCount(): Int = items.size
  35.  
  36.     override fun onBindViewHolder(holder: AnyViewModelHolder<MODEL, BINDING>, position: Int) {
  37.         holder.bind(items[position])
  38.  
  39.         clickHandler?.let { handler ->
  40.             holder.itemView.setOnClickListener {
  41.                 handler(items[position])
  42.             }
  43.         }
  44.  
  45.         onBindedViewHolder(holder, items[position])
  46.     }
  47.  
  48.     fun replace(newItems: List<MODEL>, notify: Boolean = true) {
  49.         items.clear()
  50.         items.addAll(newItems)
  51.         if (notify) notifyDataSetChanged()
  52.     }
  53.  
  54. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top