Android-如何更好的刷新RecyclerView

如何刷新RecyclerView?

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

相关方法

inline fun  ObservableArrayList.communicateWithAdapter(adapter: RecyclerView.Adapter<*>) =
    addOnListChangedCallback(object :
        ObservableList.OnListChangedCallback>() {
        @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()
val recyclerAdapter = RecyclerAdapter(context, list)

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

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

你可能感兴趣的:(Android-如何更好的刷新RecyclerView)