若是遇到须要显示多种layout的状况,不少时候咱们是经过把全部的layout写到一个文件中,经过显示和隐藏控件的方式进行控制。这样作明显很差的一点是由于要进行多余的绘制,会影响性能。还有,若是遇到错误想要显示错误的layout的时候怎样写比较优雅呢。 为了解决这样的问题,就出现了Groupie
的库。android
在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"
复制代码
须要多少ViewType
,咱们就须要建立多少个BindableItem
。github
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) }
}
}
复制代码
建立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
}
复制代码
以往是建立ListAdapter
等,可是在这里咱们须要建立Groupie
提供的GroupAdapter
。而后经过GroupeAdapter.update
方法对List<Section>
数据进行更新。app
private val adapter: GroupAdapter<GroupieViewHolder> = GroupAdapter()
binding.recyclerview.adapter = adapter
val sections = generateData()
adapter.update(sections)
复制代码
为了解决能够在一个RecyclerView
中显示多个不一样的ViewType
的痛点,谷歌推出了MergeAdapter
。ide
跟MergeAdapter
相比较Groupie
的优点在于能够混着使用ViewType
,可是MergeAdapter
不能够。post
也就是说MergeAdapter
只能是先显示完第一种ViewType
,而后才能显示第二种ViewType
。性能
固然MergeAdapter
的优点是写法优雅,易读。gradle
MergeAdapter的教程: juejin.im/post/5e903f…ui
Android ConstraintLayout的易懂教程: juejin.im/post/5ea50a…
Github: github.com/HyejeanMOON…