在RecyclerView中能夠應對多個ViewType的庫--Groupie

1. 簡介

若是遇到須要顯示多種layout的狀況,不少時候咱們是經過把全部的layout寫到一個文件中,經過顯示和隱藏控件的方式進行控制。這樣作明顯很差的一點是由於要進行多餘的繪製,會影響性能。還有,若是遇到錯誤想要顯示錯誤的layout的時候怎樣寫比較優雅呢。 爲了解決這樣的問題,就出現了Groupie的庫。android

2. 使用方法

2.1 引入外部的庫

build.gradle中加入下列代碼來引用外部的庫。git

implementation "com.xwray:groupie:2.7.0"
    implementation "com.xwray:groupie-kotlin-android-extensions:2.7.0"
    implementation "com.xwray:groupie-databinding:2.7.0"
複製代碼

2.2 建立BindableItem

須要多少ViewType,咱們就須要建立多少個BindableItemgithub

data class ListBindableItem(
    val str: String,
    val onClick: (String) -> Unit
) : BindableItem<ItemListBinding>() {
    // 返回layout的Int值
    override fun getLayout(): Int {
        return R.layout.item_list
    }
    // 綁定數據
    override fun bind(viewBinding: ItemListBinding, position: Int) {
        viewBinding.textview.text = str
        viewBinding.textview.setOnClickListener { onClick(str) }
    }
}
複製代碼

2.3 建立須要顯示的Section數組

建立List<Section>,而後把想顯示的數據傳入到BindableItem,而後進行建立,並傳入到Section中。數組

private fun generateData(): List<Section> {
        val prefix = "MOON"
        val result: ArrayList<Section> = arrayListOf()
        for (i in 0..40) {
            val section = Section().apply {
                if (i % 2 == 0) {
                    add(ListBindableItem(prefix + i, onClick))
                } else {
                    add(ListTwoBindableItem(prefix + i, onClick))
                }
            }
            result.add(section)
        }
        return result
    }
複製代碼

2.4 建立Adapter並更新Section

以往是建立ListAdapter等,可是在這裏咱們須要建立Groupie提供的GroupAdapter。而後經過GroupeAdapter.update方法對List<Section>數據進行更新。app

private val adapter: GroupAdapter<GroupieViewHolder> = GroupAdapter()
binding.recyclerview.adapter = adapter
val sections = generateData()
adapter.update(sections)
複製代碼

3. 評價

爲了解決能夠在一個RecyclerView中顯示多個不一樣的ViewType的痛點,谷歌推出了MergeAdapteride

MergeAdapter相比較Groupie的優點在於能夠混着使用ViewType,可是MergeAdapter不能夠。post

也就是說MergeAdapter只能是先顯示完第一種ViewType,而後才能顯示第二種ViewType性能

固然MergeAdapter的優點是寫法優雅,易讀。gradle

4. Github

MergeAdapter的教程: juejin.im/post/5e903f…ui

Android ConstraintLayout的易懂教程: juejin.im/post/5ea50a…

Github: github.com/HyejeanMOON…

相關文章
相關標籤/搜索