Kotlin encapsulation RecyclerView Adapter instance tutorial

  • 2021-10-11 19:40:20
  • OfStack

Preface

Kotlin is becoming more and more popular, and it develops rapidly under the impetus of Google. Most of the current projects use Kotlin, and its concise syntax sugar can really reduce a lot of code.

There are many encapsulations of Adapter on GitHub, but most of them are too good. Yes, they are too simple to use. Simple to use and strong encapsulation will lead to increased flexibility and code complexity. Whoever uses them knows, of course, there are also simple encapsulations.

Here, I use the simple syntax of Kotlin to encapsulate 1 times again.

Take a look at the use first

Use of single type


val adapter=recyclerView.setUp(users, R.layout.item_layout, { holder, item ->
   var binding = DataBindingUtil.getBinding<ItemLayoutBinding>(holder.itemView)
   binding.nameText.text = item.name
   ...
  })

Multi-type use


recyclerView.setUP(users,
    listItems = *arrayOf(
      ListItem(R.layout.item_layout, { holder, item ->
       var binding = DataBindingUtil.getBinding<ItemLayoutBinding>(holder.itemView)
       binding?.nameText?.text = item.name
       ...
      }, {
       Snackbar.make(window.decorView, it.name, Snackbar.LENGTH_SHORT).show()
      }),
      ListItem(R.layout.item_layout2, { holder, item ->
       val nameText: TextView = holder.getView(R.id.nameText)
       nameText.text = item.name
       ...
      }, {

      })
    ))

It's so simple to use, let's see if the code is over-encapsulated

Base Class for Adapter


abstract class AbstractAdapter<ITEM> constructor(protected var itemList: List<ITEM>)
 : RecyclerView.Adapter<AbstractAdapter.Holder>() {

 override fun getItemCount() = itemList.size

 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
  val view = createItemView(parent, viewType)
  val viewHolder = Holder(view)
  val itemView = viewHolder.itemView
  itemView.setOnClickListener {
   val adapterPosition = viewHolder.adapterPosition
   if (adapterPosition != RecyclerView.NO_POSITION) {
    onItemClick(itemView, adapterPosition)
   }
  }
  return viewHolder
 }


 fun update(items: List<ITEM>) {
  updateAdapterWithDiffResult(calculateDiff(items))
 }

 private fun updateAdapterWithDiffResult(result: DiffUtil.DiffResult) {
  result.dispatchUpdatesTo(this)
 }

 private fun calculateDiff(newItems: List<ITEM>) =
   DiffUtil.calculateDiff(DiffUtilCallback(itemList, newItems))

 fun add(item: ITEM) {
  itemList.toMutableList().add(item)
  notifyItemInserted(itemList.size)
 }

 fun remove(position: Int) {
  itemList.toMutableList().removeAt(position)
  notifyItemRemoved(position)
 }

 final override fun onViewRecycled(holder: Holder) {
  super.onViewRecycled(holder)
  onViewRecycled(holder.itemView)
 }

 protected open fun onViewRecycled(itemView: View) {
 }

 protected open fun onItemClick(itemView: View, position: Int) {
 }

 protected abstract fun createItemView(parent: ViewGroup, viewType: Int): View

 class Holder(itemView: View) : RecyclerView.ViewHolder(itemView) {
  private val views = SparseArray<View>()

  fun <T : View> getView(viewId: Int): T {
   var view = views[viewId]
   if (view == null) {
    view = itemView.findViewById(viewId)
    views.put(viewId, view)
   }
   return view as T
  }
 }
}

Implementation of subclass and extension of RecyclerView


class SingleAdapter<ITEM>(items: List<ITEM>,
       private val layoutResId: Int,
       private val bindHolder: (Holder, ITEM) -> Unit)
 : AbstractAdapter<ITEM>(items) {

 private var itemClick: (ITEM) -> Unit = {}

 constructor(items: List<ITEM>,
    layoutResId: Int,
    bindHolder: (Holder, ITEM) -> Unit,
    itemClick: (ITEM) -> Unit = {}) : this(items, layoutResId, bindHolder) {
  this.itemClick = itemClick
 }

 override fun createItemView(parent: ViewGroup, viewType: Int): View {
  var view = parent inflate layoutResId
  if (view.tag?.toString()?.contains("layout/") == true) {
   DataBindingUtil.bind<ViewDataBinding>(view)
  }
  return view
 }

 override fun onBindViewHolder(holder: Holder, position: Int) {
  bindHolder(holder, itemList[position])
 }

 override fun onItemClick(itemView: View, position: Int) {
  itemClick(itemList[position])
 }
}


class MultiAdapter<ITEM : ListItemI>(private val items: List<ITEM>,
          private val bindHolder: (Holder, ITEM) -> Unit)
 : AbstractAdapter<ITEM>(items) {

 private var itemClick: (ITEM) -> Unit = {}
 private lateinit var listItems: Array<out ListItem<ITEM>>

 constructor(items: List<ITEM>,
    listItems: Array<out ListItem<ITEM>>,
    bindHolder: (Holder, ITEM) -> Unit,
    itemClick: (ITEM) -> Unit = {}) : this(items, bindHolder) {
  this.itemClick = itemClick
  this.listItems = listItems
 }

 override fun createItemView(parent: ViewGroup, viewType: Int): View {
  var view = parent inflate getLayoutId(viewType)
  if (view.tag?.toString()?.contains("layout/") == true) {
   DataBindingUtil.bind<ViewDataBinding>(view)
  }
  return view
 }

 private fun getLayoutId(viewType: Int): Int {
  var layoutId = -1
  listItems.forEach {
   if (it.layoutResId == viewType) {
    layoutId = it.layoutResId
    return@forEach
   }
  }
  return layoutId
 }

 override fun getItemViewType(position: Int): Int {
  return items[position].getType()
 }

 override fun onBindViewHolder(holder: Holder, position: Int) {
  bindHolder(holder, itemList[position])
 }

 override fun onItemClick(itemView: View, position: Int) {
  itemClick(itemList[position])
 }
}


fun <ITEM> RecyclerView.setUp(items: List<ITEM>,
        layoutResId: Int,
        bindHolder: (AbstractAdapter.Holder, ITEM) -> Unit,
        itemClick: (ITEM) -> Unit = {},
        manager: RecyclerView.LayoutManager = LinearLayoutManager(this.context)): AbstractAdapter<ITEM> {
 val singleAdapter by lazy {
  SingleAdapter(items, layoutResId, { holder, item ->
   bindHolder(holder, item)
  }, {
   itemClick(it)
  })
 }
 layoutManager = manager
 adapter = singleAdapter
 return singleAdapter
}


fun <ITEM : ListItemI> RecyclerView.setUP(items: List<ITEM>,
           manager: RecyclerView.LayoutManager = LinearLayoutManager(this.context),
           vararg listItems: ListItem<ITEM>): AbstractAdapter<ITEM> {

 val multiAdapter by lazy {
  MultiAdapter(items, listItems, { holder, item ->
   var listItem: ListItem<ITEM>? = getListItem(listItems, item)
   listItem?.bindHolder?.invoke(holder, item)
  }, { item ->
   var listItem: ListItem<ITEM>? = getListItem(listItems, item)
   listItem?.itemClick?.invoke(item)
  })
 }
 layoutManager = manager
 adapter = multiAdapter
 return multiAdapter
}

private fun <ITEM : ListItemI> getListItem(listItems: Array<out ListItem<ITEM>>, item: ITEM): ListItem<ITEM>? {
 var listItem: ListItem<ITEM>? = null
 listItems.forEach {
  if (it.layoutResId == item.getType()) {
   listItem = it
   return@forEach
  }
 }
 return listItem
}

class ListItem<ITEM>(val layoutResId: Int,
      val bindHolder: (holder: AbstractAdapter.Holder, item: ITEM) -> Unit,
      val itemClick: (item: ITEM) -> Unit = {})


interface ListItemI {
 fun getType(): Int
}

ok, all the core code, no, also do not intend to release rar, to use direct clone down to introduce the project, this is the best way, because it is not complicated, to change at any time.

Looking at the above multi-type use, we can find that it supports ordinary Layout and DataBinding Layout, which is also a feature of this library and does not need redundant processing.

1. Ordinary Layout is treated like this


ListItem(R.layout.item_layout2, { holder, item ->
       val nameText: TextView = holder.getView(R.id.nameText)
       nameText.text = item.name
      }

Operate View through Holder, which is cached.


DataBinding Layout
ListItem(R.layout.item_layout, { holder, item ->
       var binding = DataBindingUtil.getBinding<ItemLayoutBinding>(holder.itemView)
       binding.nameText.text = item.name
      }

If you only know which Layout is, you can deal with it correspondingly. The Holder processing mode can also deal with DataBinding Layout, so you should know.

Here, some people may ask why not use the Layout View search method of Kotlin directly. ? ?

That code looks simple, but the current Studio support for this is not very good, often reported red, programmers see red will fidgety ah! ! If you still like it, it is also very simple to realize it. It is OK to change it to the expansion of View. You can try it yourself.

Because only the unchanged parts are encapsulated here, there are not many gorgeous functions to add head and feet, but one kind of click event is built in. Of course, click event can also be realized by ItemTouchHelper, which is ok.

In this way, you don't have to write a large string of Adaper every time. Can you make a pot of tea and blow your breath happily?

Other libraries can be reused by Item, can yours?

Mm-hmm,,? Yes

For example


val item: (AbstractAdapter.Holder, User) -> Unit = { holder, user ->

  }

Another example is


ListItem(R.layout.item_layout, { holder, item ->
       var binding = DataBindingUtil.getBinding<ItemLayoutBinding>(holder.itemView)
      }, {// Click event 
       Snackbar.make(window.decorView, it.name, Snackbar.LENGTH_SHORT).show()
      })

Is 1 kind can be defined as long as 1 place and then set in it, reuse is also difficult to defeat it. It can only be said that Kotlin grammar is good.

Ok, this library is introduced here, thank you.

Code address

Reference link

Inspired by the following great god, but I basically rewrote it

https://github.com/armcha/Kadapter

Summarize


Related articles: