前言
EpoxyRecyclerView很好地支持列表中有多种布局类型,让我们在使用的过程无需去关注ViewType,而是直接为每个类型定义对应的Model就可以了。它会自动为我们做了差分,还提高了的性能。
EpoxyRecyclerView的Github地址:
https://github.com/airbnb/epoxy
EpoxyRecyclerView的使用
添加依赖:
在app的build.gradle文件中添加
apply plugin: 'kotlin-kapt'
然后加入依赖:
implementation 'com.airbnb.android:epoxy:3.7.0'
kapt 'com.airbnb.android:epoxy-processor:3.7.0'
使用:
1.与使用RecyclerView一样,在布局文件里边加入EpoxyRecyclerView
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<com.airbnb.epoxy.EpoxyRecyclerView
android:id="@+id/epoxy_rv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
2.创建一个Controller:
EpoxyController有好几个子类,可根据类型参数的个数来选择继承,以下例子继承的是一个参数的TypedEpoxyController,如果有两个参数的话可继承Typed2EpoxyController,以此类推,最高的数字为4:
class HeaderController() : TypedEpoxyController<List<String>>() {
override fun buildModels(titles: List<String>?) {
}
}
继承后需要实现buildModels方法,参数为我们展示需要用到的数据。
3.创建Model:
继承EpoxyModelWithHolder,并用注解EpoxyModelClass来标记这是一个Model类,然后会生成对应的类使用。Model类需要是抽象的:
@EpoxyModelClass(layout = R.layout.header_view)
abstract class HeaderModel : EpoxyModelWithHolder<Holder>(){
@EpoxyAttribute
lateinit var title: String
override fun bind(holder: Holder) {
holder.tvHeader.text =title
}
}
class Holder :EpoxyHolder(){
lateinit var tvHeader : TextView
override fun bindView(itemView: View) {
tvHeader = itemView.findViewById(R.id.tv_header)
}
}
layout属性表示对应的布局文件。
写好Model类之后,build一下,然后就可以在controller中添加Model了,这里只用一种Model,在实际开发中可根据对应的条件添加相应的Model:
class HeaderController(private val callback: OriginHeaderModel.OnBtnCallback) : TypedEpoxyController<List<String>>() {
override fun buildModels(titles: List<String>?) {
originHeader {
id("button")
callback(callback)
}
titles?.forEachIndexed {
index