其他分享
首页 > 其他分享> > android开发——RecyclerView通用adapter Kotlin版

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)

标签:ViewHolder,val,Int,Kotlin,adapter,text,android,RecyclerView,view
来源: https://www.cnblogs.com/maplerain/p/16691563.html