BaseRecyclerViewAdapter封装
<p><code>abstract class BaseRecyclerViewAdapter<D, VH : BaseRecyclerViewAdapter.BaseViewHolder>(layoutResId: Int, data: MutableList<D>) : RecyclerView.Adapter<VH>() {
open var layoutResId: Int = 0 //item资源Id
open var data: List<D> = data //数据集合
open var view: View? = null
init {
if (layoutResId != 0)
this.layoutResId = layoutResId
else
throw NullPointerException("请设置Item资源Id")
}
override fun onBindViewHolder(holder: VH, position: Int) {
bindData(holder, data[position],position)
}
override fun getItemCount(): Int {
return data.size
}
/**
* 绑定数据
* @param holder
* *
* @param data
*/
protected abstract fun bindData(holder: VH, data: D,position: Int)
open class BaseViewHolder : RecyclerView.ViewHolder{
open var mView: View? = null
constructor(view: View): super(view){
mView = view
}
}
}
</code></p>
<p>在Activity中定义MyRecyclerViewAdapter</p>
<p><code>
inner class MyRecyclerViewAdapter<VH: MyViewHolder>(layoutResId: Int, data: MutableList<GirlBean>) : BaseRecyclerViewAdapter<GirlBean, VH>(layoutResId, data) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
view = LayoutInflater.from(parent.context).inflate(layoutResId, parent, false)
return MyViewHolder(view!!) as VH
}
override fun bindData(holder: VH, data: GirlBean,position: Int) {
this@MainActivity.loadImg(data.url,holder.imageview!!)
holder.textview?.text = data.who
loadImg(data.url, holder.imageview!!)
holder.imageview?.setOnClickListener { mListener.onItemClick(position, holder.imageview!!) }
}
}
inner class MyViewHolder(view: View) : BaseRecyclerViewAdapter.BaseViewHolder(view) {
var imageview: ImageView? = null
var textview: TextView? = null
init {
imageview = mView?.findViewById(R.id.imageview) as ImageView?
textview = mView?.findViewById(R.id.textview) as TextView?
}
}</code></p>
<p>初始化时使用</p>
<p><code>
mAdapter = MyRecyclerViewAdapter(R.layout.item_girl,mList)
recyclerview.adapter = mAdapter
</code></p>