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)

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/289282.html

(0)
上一篇 2022年9月14日 01:40
下一篇 2022年9月14日 02:13

相关推荐

发表回复

登录后才能评论