本文主要是介绍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)
这篇关于android开发——RecyclerView通用adapter Kotlin版的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!