Android-如何更好的刷新RecyclerView

2022-01-09  本文已影响0人  Cosecant

如何刷新RecyclerView?

首先刷新RecyclerView会使用Adapter,数据源采用List,那么我们怎样去刷新RecyclerView更合适?看看下面的方法,或许能适用于你。

相关方法

inline fun <reified T> ObservableArrayList<T>.communicateWithAdapter(adapter: RecyclerView.Adapter<*>) =
    addOnListChangedCallback(object :
        ObservableList.OnListChangedCallback<ObservableList<*>>() {
        @SuppressLint("NotifyDataSetChanged")
        override fun onChanged(sender: ObservableList<*>?) {
            adapter.notifyDataSetChanged()
        }

        override fun onItemRangeChanged(
            sender: ObservableList<*>?,
            positionStart: Int,
            itemCount: Int
        ) {
            adapter.notifyItemRangeChanged(positionStart, itemCount)
        }

        override fun onItemRangeInserted(
            sender: ObservableList<*>?,
            positionStart: Int,
            itemCount: Int
        ) {
            adapter.notifyItemRangeInserted(positionStart, itemCount)
        }

        override fun onItemRangeMoved(
            sender: ObservableList<*>?,
            fromPosition: Int,
            toPosition: Int,
            itemCount: Int
        ) {
            adapter.notifyItemMoved(fromPosition, toPosition)
        }

        override fun onItemRangeRemoved(
            sender: ObservableList<*>?,
            positionStart: Int,
            itemCount: Int
        ) {
            adapter.notifyItemRangeRemoved(positionStart, itemCount)
        }
    })

调用案例

val list = ObservableList<T>()
val recyclerAdapter = RecyclerAdapter(context, list)

fun create(){
    list.communicateWithAdapter(adapter)
}

fun doSth(){
    list.add(T)
    list.remove(T)
    list.clear()
    //...
}

上一篇下一篇

猜你喜欢

热点阅读