首页 > 解决方案 > 如何在 android 中将 ListUpdateCallback 添加到 ListAdapter

问题描述

所以我有一个抽象类,在我添加 ListUpdateCallback 后它不起作用任何想法我该如何处理?我添加 ListUpdateCallback 的原因是在列表中添加项目或删除项目列表后不会更新所以也许这应该工作,有什么解决方案吗?

abstract class BaseGenericListAdapter<T : Any>(
    @IdRes val layoutId: Int,
) : ListAdapter<T, BaseViewHolder>(BaseItemCallback<T>()) {

   private val TAG="AppDebug BaseGenericListAdapter"

    override fun getItemViewType(position: Int) = layoutId

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
        val root = LayoutInflater.from(parent.context).inflate(
            viewType, parent, false
        )
        return BaseViewHolder(root as ViewGroup)
    }

    var list: List<T>
        get() = currentList
        set(value) = submitList(value)




    override fun getItemCount() = list.size


   internal inner class RecyclerChangeCallback(
        private val adapter: BaseGenericListAdapter<T>
    ) : ListUpdateCallback {

        override fun onChanged(position: Int, count: Int, payload: Any?) {
            adapter.notifyItemRangeChanged(position, count, payload)
        }

        override fun onInserted(position: Int, count: Int) {
            adapter.notifyItemRangeChanged(position, count)
        }

        override fun onMoved(fromPosition: Int, toPosition: Int) {
            adapter.notifyDataSetChanged()
        }

        override fun onRemoved(position: Int, count: Int) {
            adapter.notifyDataSetChanged()
        }
    }

    val DIFF_CALLBACK = object : DiffUtil.ItemCallback<T>() {
        override fun areItemsTheSame(oldItem: T, newItem: T) = oldItem.toString() == newItem.toString()

        @SuppressLint("DiffUtilEquals")
        override fun areContentsTheSame(oldItem: T, newItem: T) = oldItem == newItem
    }


    private val newDiffer =
        AsyncListDiffer(
            RecyclerChangeCallback(this),
            AsyncDifferConfig.Builder(DIFF_CALLBACK).build()
        )


}



class BaseViewHolder(container: ViewGroup) : RecyclerView.ViewHolder(container)

class BaseItemCallback<T : Any> : DiffUtil.ItemCallback<T>() {
    override fun areItemsTheSame(oldItem: T, newItem: T) = oldItem.toString() == newItem.toString()

    @SuppressLint("DiffUtilEquals")
    override fun areContentsTheSame(oldItem: T, newItem: T) = oldItem == newItem
}




有谁知道必须解决这个问题?我试图拥有基本适配器,但我有更新列表的问题

标签: androidkotlin

解决方案


这可能有助于使 BaseGenericListAdapter 实现 ListUpdateCallback 并将其从 RecyclerChangeCallback 中删除并将您的覆盖保持在它们所在的位置。


推荐阅读