@cxm-2016
2016-07-27T17:20:10.000000Z
字数 1400
阅读 1538
adapter
viewholder
import android.support.v7.widget.RecyclerView
import android.util.SparseArray
import android.view.View
import android.widget.TextView
/**
* Created by cxm on 16/7/27.
*/
class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val sparseArray = SparseArray<View>(8)
fun <T : View> getView(viewId: Int): T {
var view = sparseArray[viewId]
if (view == null) {
view = itemView.findViewById(viewId)
sparseArray.put(viewId, view)
}
return view as T
}
fun setText(viewId: Int, text: String): BaseViewHolder {
getView<TextView>(viewId).text = text
return this
}
}
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import java.util.*
/**
* Created by cxm on 16/7/27.
*/
abstract class CommonBaseAdapter<T>(var rv: RecyclerView, var itemLayout: Int, var inflater: LayoutInflater) : RecyclerView.Adapter<BaseViewHolder>() {
protected var datas: ArrayList<T> = ArrayList()
set(value) {
datas = value
notifyDataSetChanged()
}
fun addData(data: T) {
datas.add(data)
}
override fun getItemCount(): Int = datas.size
override fun onBindViewHolder(holder: BaseViewHolder?, position: Int) = bindViewData(holder, datas[position], position)
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): BaseViewHolder {
var view = inflater.inflate(itemLayout, parent, false)
var viewHolder = BaseViewHolder(view)
viewHolder.setIsRecyclable(true)
return viewHolder
}
abstract fun bindViewData(holder: BaseViewHolder?, item: T, position: Int)
}