首页 > 解决方案 > 如何提高 RecyclerView 的性能?

问题描述

当我在 RecyclerView 中使用“重”视图时,它在我滚动时会滞后并显示像这个动画这样的奇怪工件。当我在 RecyclerView 中使用“轻”视图时,它可以正常工作。这发生在所有具有强大特性的设备事件上。请告诉我,我做错了什么?我使用 RoomDB 在适配器中保存数据、分页逻辑。

const val VIEW_HOLDER = 12
const val PROGRESS = 13

abstract class BasePaginationAdapter<T: FMBase>(private val callback: PaginationAdapterCallback<T>): RecyclerView.Adapter<BasePaginationAdapter.BaseHolder>() {
    protected val items: ArrayList<T> = ArrayList()
    protected var isPaginate = true
    protected var pageCount = SYNC_MIN_PAGE_ITEMS

    override fun getItemViewType(position: Int): Int {
        if (position >= items.size) {
            return PROGRESS
        }
        return VIEW_HOLDER
    }

    override fun onCreateViewHolder(p0: ViewGroup, p1: Int): BaseHolder {
        return if (p1 == PROGRESS) {
            ProgressHolder(LayoutInflater.from(p0.context), p0)
        } else {
            getViewHolder(LayoutInflater.from(p0.context), p0, p1)
        }
    }

    override fun getItemCount(): Int {
        return if (isPaginate) {
            items.size + 1
        } else {
            items.size
        }
    }

    open fun addItems(data: Array<T>) {
        if (isPaginate && data.size < pageCount) {
            isPaginate = false
        }
        notifyItemRemoved(items.size)
        if (data.isNotEmpty()) {
            val pos = items.size
            items.addAll(data)
            if (pos > 0) {
                notifyItemRangeInserted(pos, data.size)
            } else {
                notifyDataSetChanged()
            }
        }
    }

    fun clear() {
        items.clear()
        isPaginate = true
        notifyItemRangeRemoved(0, items.size)
    }

    override fun onBindViewHolder(holder: BaseHolder, position: Int) {
        if (position == items.size - 1 && isPaginate) {
            callback.onPaginate(items.size, pageCount)
        }
    }

    interface PaginationAdapterCallback<T: FMBase> {
        fun onItemClick(item: T)
        fun onPaginate(offset: Int, count: Int)
    }

    abstract fun getViewHolder(inflater: LayoutInflater, root: ViewGroup, viewType: Int): BaseHolder

    abstract class BaseHolder(itemView: View): RecyclerView.ViewHolder(itemView)

    class ProgressHolder(inflater: LayoutInflater, root: ViewGroup):
        BaseHolder(inflater.inflate(R.layout.view_progressbar_bottom, root, false))
}

标签: androidperformancekotlinandroid-recyclerview

解决方案


推荐阅读