android RecyclerView adapter 封装

Posted 编程小弟弟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android RecyclerView adapter 封装相关的知识,希望对你有一定的参考价值。

package com.durang.base

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

class BaseAdapter<T>(val layoutResourceId: Int, val items: List<T>, val init: (View, T) -> Unit) :
    RecyclerView.Adapter<BaseAdapter.ViewHolder<T>>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder<T> {
        val view = LayoutInflater.from(parent.context).inflate(layoutResourceId,null)
        return ViewHolder(view, init)
    }

    override fun onBindViewHolder(holder: ViewHolder<T>, position: Int) {
        holder.bindForecast(items[position])
    }

    override fun getItemCount() = items.size

    class ViewHolder<in T>(view: View, val init: (View, T) -> Unit) : RecyclerView.ViewHolder(view) {
        fun bindForecast(item: T) {
            with(item) {
                init(itemView, item)
            }
        }
    }
}
var adapter: BaseAdapter<Goodsinfo.Goods>? = null
adapter = BaseAdapter(R.layout.item_goods_release,goods){
        view, goods ->
    view.tvGtitle.text = goods.gtitle
    view.tvGdesc.text = goods.gdesc
    view.tvGTime.text = MyUtils.TimestampToDate(goods.gtime!!,"yyyy/MM/dd HH:mm")
    view.tvGbrowse.text = "浏览量:"+goods.gbrowse
}

以上是关于android RecyclerView adapter 封装的主要内容,如果未能解决你的问题,请参考以下文章

在Android中滚动recyclelerview时,Edittext值消失

Android中RecyclerView嵌套RecyclerView或嵌套ListView

Android RecyclerView嵌套RecyclerView

Android之RecyclerView介绍

Android:RecyclerView里面的RecyclerView,滚动到底部

Android教程2020 - RecyclerView获取滑动距离