android开发——RecyclerView通用adapter Kotlin版
MyAdapter类
class MyAdapter<E>(
val recyclerView:RecyclerView,
val listItemId:Int,
val dataResource:List<E>,
val func: (data: Any?, view: View) -> Unit,
var len:Int?=null
):RecyclerView.Adapter<MyAdapter<E>.ViewHolder>() {
init { recyclerView.adapter = this }
inner class ViewHolder(val view:View) :RecyclerView.ViewHolder(view)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(listItemId, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
func(dataResource.get(position),holder.view)
}
override fun getItemCount(): Int {
return len?:dataResource.size
}
}
用例示范:
// 需要用到四个参数分别是RecyclerView实例,子项布局视图,数据源(List类),回调方法
var adapter = MyAdapter<TestBean>(a.recycler_list, R.layout.list_item_view, list, { data, view ->
(data as TestBean).let {
view.apply {
name_text.text = it.name
age_text.text = it.age.toString()
work_number.text = it.workNumber
}
}
})
adapter.len = 12
adapter.recyclerView?.layoutManager = LinearLayoutManager(a)
本文来自博客园,作者:maplerain,转载请注明原文链接:https://www.cnblogs.com/maplerain/p/16691563.html 博主B站