Skip to content

A simple recyclerView adapter using ListAdapter, DataBinding and DiffUtil

License

Notifications You must be signed in to change notification settings

SongDanielLi/SongAdapterLib

Repository files navigation

SongAdapterLib

A simple recyclerView adapter using ListAdapter, DataBinding and DiffUtil

Setup gradle

Step 1. Add the JitPack repository to your build file

Add it in your root build.gradle at the end of repositories:

allprojects {
  repositories {
    ...
    maven { url 'https://jitpack.io' }
  }
}

Step 2. Add the dependency

dependencies {
    implementation 'com.github.SongDanielLi:SongAdapterLib:Tag'
}

Example

1. create your own item with databinding

Set up databinding

class CardRow(override val value: String): BindingItem<CardViewBinding, String>() {
    override val viewType: Int
        get() = R.layout.card_view

    override fun createBinding(inflater: LayoutInflater, parent: ViewGroup, viewType: Int): CardViewBinding {
        return CardViewBinding.inflate(inflater, parent, false)
    }

    override fun onBind(binding: CardViewBinding) {
        binding.txtCard.text = value
    }

    // implement onClick listener
    override fun onClickListener(view: View, position: Int) {
        Toast.makeText(view.context, "Click: $position", Toast.LENGTH_LONG).show()
    }
}

2. Set the adapter

val adapter = BindingAdapter()
recyclerView.adapter = adapter

// create item
val row = CardRow("Test")
// add to adapter
adapter.submitList(listOf(row))

Reference

Android Kotlin Fundamentals: DiffUtil and data binding with RecyclerView

License

License: MIT