是一个超级轻量级的能够快速实现 RecyclerView 复杂适配器的工具库。 php
1.在 root's build.gradle 中加入 jcenter 仓库android
allprojects {
repositories {
...
jcenter()
}
}
复制代码
2.在 app's build.gradle 中开启 databindinggit
android {
...
dataBinding {
enabled = true
}
}
复制代码
3.在 app's build.gradle 中添加依赖(请使用最新版本)github
dependencies {
...
implementation 'com.xuyefeng:magicadapter:1.0.1'
}
复制代码
1.建立 RecyclerView item 布局文件 image_item_layout.xmlapp
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="item" type="com.blue.helloadapter.ImageItem" />
</data>
<RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp">
<ImageView android:id="@+id/iv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" />
</RelativeLayout>
</layout>
复制代码
请注意这里的声明的 XXXItem 的 name 必须为 item
ide
2.建立 item 布局文件对应的 XXXItem 即 ImageItem工具
class ImageItem(
val resId: Int
) : BaseItem() {
override fun getLayout(): Int = R.layout.image_item_layout
override fun onBinding(binding: ViewDataBinding) {
(binding as ImageItemLayoutBinding).apply {
iv.setImageResource(resId)
iv.setOnClickListener {
Toast.makeText(iv.context, "click image on ${getViewHolder()?.adapterPosition}", Toast.LENGTH_SHORT).show()
}
}
}
}
复制代码
这里针对 BaseItem 说明一下:布局
3.用一样的方法建立 TextItem 和 ButtonItem,接下来就能够添加数据了gradle
val adapter = MagicAdapter()
adapter.addItem(ImageItem(R.drawable.s1))
adapter.addItem(TextItem())
adapter.addItem(ButtonItem())
recyclerView.adapter = adapter
复制代码
4.若是你须要回调,能够像这样动画
adapter.onItemClickListener = object : OnItemClickListener {
override fun onItemClick(holder: ItemViewHolder)
val position = holder.adapterPosition
val item = holder.item
val binding = holder.binding
...
}
}
复制代码
到这里就结束了,为一个 RecyclerView 添加复杂适配器原来能够如此简单。
最后再附上:github地址传送门 喜欢就start一下呗