在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…

相关文章
相关标签/搜索