您好,登錄后才能下訂單哦!
如何在Kotlin中封裝RecyclerView Adapter?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
單類型的使用
val adapter=recyclerView.setUp(users, R.layout.item_layout, { holder, item -> var binding = DataBindingUtil.getBinding<ItemLayoutBinding>(holder.itemView) binding.nameText.text = item.name ... })
多類型的使用
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 ... }, { }) ))
使用就是如此簡單,再來看下代碼是不是過度封裝
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 } } }
子類的實現和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,所有核心代碼,沒有了,也不打算發布rar,要用的直接clone下來引入項目,這是最好的方式,因為不復雜,要改隨時可以改。
看上面的多類型的使用,可以發現它是支持普通Layout和DataBinding Layout的,這也是本庫的一個特色,不需要多余的處理。
1.普通的Layout 這樣處理
ListItem(R.layout.item_layout2, { holder, item -> val nameText: TextView = holder.getView(R.id.nameText) nameText.text = item.name }
通過Holder來操作View,里面有做緩存的。
DataBinding Layout ListItem(R.layout.item_layout, { holder, item -> var binding = DataBindingUtil.getBinding<ItemLayoutBinding>(holder.itemView) binding.nameText.text = item.name }
是不是只要自己知道是哪中Layout,對應處理就可以了,Holder處理方式也是可以處理DataBinding Layout的,要知曉。
這里提下,可能有人會問干嘛不直接用Kotlin的Layout View 查找方法???
那樣代碼看起來是簡單,但是現在的Studio 對這個的支持不是很好,經常報紅,程序員看到紅會煩躁啊!!如果還是喜歡的話實現也很簡單,改成View的擴展返回就可以了,可以自己動手試下哦。
因為這里只是對不變的部分進行了封裝,沒有很多華麗麗的添加頭部、腳部啥的功能,點擊事件倒是內置了一種,當然點擊事件還可以用ItemTouchHelper實現,都是可以的。
這樣每次就不用寫一大串的Adaper了,是不是可以開心地泡壺茶,吹口氣了。
別的庫都可以Item復用的,你的可以嗎?
嗯嗯、、?可以的
比如
val item: (AbstractAdapter.Holder, User) -> Unit = { holder, user -> }
再比如
ListItem(R.layout.item_layout, { holder, item -> var binding = DataBindingUtil.getBinding<ItemLayoutBinding>(holder.itemView) }, {//點擊事件 Snackbar.make(window.decorView, it.name, Snackbar.LENGTH_SHORT).show() })
看完上述內容,你們掌握如何在Kotlin中封裝RecyclerView Adapter的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。