[关闭]
@cxm-2016 2016-07-27T17:20:10.000000Z 字数 1400 阅读 1538

RecyclerView自定义CommonBaseAdapter

adapter viewholder


  1. import android.support.v7.widget.RecyclerView
  2. import android.util.SparseArray
  3. import android.view.View
  4. import android.widget.TextView
  5. /**
  6. * Created by cxm on 16/7/27.
  7. */
  8. class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
  9. private val sparseArray = SparseArray<View>(8)
  10. fun <T : View> getView(viewId: Int): T {
  11. var view = sparseArray[viewId]
  12. if (view == null) {
  13. view = itemView.findViewById(viewId)
  14. sparseArray.put(viewId, view)
  15. }
  16. return view as T
  17. }
  18. fun setText(viewId: Int, text: String): BaseViewHolder {
  19. getView<TextView>(viewId).text = text
  20. return this
  21. }
  22. }
  1. import android.support.v7.widget.RecyclerView
  2. import android.view.LayoutInflater
  3. import android.view.ViewGroup
  4. import java.util.*
  5. /**
  6. * Created by cxm on 16/7/27.
  7. */
  8. abstract class CommonBaseAdapter<T>(var rv: RecyclerView, var itemLayout: Int, var inflater: LayoutInflater) : RecyclerView.Adapter<BaseViewHolder>() {
  9. protected var datas: ArrayList<T> = ArrayList()
  10. set(value) {
  11. datas = value
  12. notifyDataSetChanged()
  13. }
  14. fun addData(data: T) {
  15. datas.add(data)
  16. }
  17. override fun getItemCount(): Int = datas.size
  18. override fun onBindViewHolder(holder: BaseViewHolder?, position: Int) = bindViewData(holder, datas[position], position)
  19. override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): BaseViewHolder {
  20. var view = inflater.inflate(itemLayout, parent, false)
  21. var viewHolder = BaseViewHolder(view)
  22. viewHolder.setIsRecyclable(true)
  23. return viewHolder
  24. }
  25. abstract fun bindViewData(holder: BaseViewHolder?, item: T, position: Int)
  26. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注