结合DataBinding的万能Adapter,使代码更简洁,快速提高开发效率的通用Adapter
Add it in your root build.gradle at the end of repositories:
《一》添加依赖:
(1)Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
(2) Add the dependency
dependencies {
implementation 'com.github.GraceJoJo:DataBindingBaseAdapter:1.0.1'
}
《二》代码中使用: (1)RecyclerView的Adapter
class ADA_RecyclerItem constructor(context: Context): CommonAdapter<DataBean, ItemLayoutBinding>(context) {
override fun convert(viewBinding: ItemLayoutBinding?, holder: ViewHolder.BindingHolder?, bean: DataBean?, position: Int) {
viewBinding!!.dataBean = bean
}
override fun itemLayoutId(): Int {
return R.layout.item_layout
}
}
Activity或Fragment使用:
val dataList= ArrayList<DataBean>() //模拟数据
recyclerview.layoutManager = LinearLayoutManager(this)
var mAdapter = ADA_RecyclerItem(this)
recyclerview.adapter = mAdapter
mAdapter.update(dataList,true)
(2)ListView或者GridView的Adapter
class ADA_ListItem constructor(context: Context): CommonAdapterListView<DataBean, ItemLayoutBinding>(context) {
override fun convert(viewBinding: ItemLayoutBinding?, holder: ViewHolderListView?, bean: DataBean?, position: Int) {
viewBinding!!.dataBean = bean
}
override fun itemLayoutId(): Int {
return R.layout.item_layout
}
}
Activity或Fragment使用:
val dataList= ArrayList<DataBean>() //模拟数据
var mAdapter = ADA_ListItem(this)
listview.adapter = mAdapter
mAdapter.update(dataList,true)
《二》实现效果:
《三》优点:
(1)在布局中就把view的数据绑定工作全做好了。
(2)在Adapter中可以省略大量重复的设置数据的代码
(3)使得代码更加简洁,一目了然,易于维护。
致谢:鸿洋大神的[BaseAdapter](https://github.com/hongyangAndroid/baseAdapter)