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)
posted @ 2022-09-14 00:51  maplerain  阅读(380)  评论(0编辑  收藏  举报