EpoxyRecyclerView的简单使用与源码分析

前言

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值