簡體   English   中英

如何使用 firebase childEventListener 更新平滑 animation 添加的 Recyclerview 新項目?

[英]How to update Recyclerview new item added with smooth animation with firebase childEventListener?

我想在使用平滑 animation 添加新項目(聊天項目)時更新 recyclerview UI。notifyDataSetChanged() 導致整個列表更新出現故障 animation。

我正在使用 firebase childEventListenior 在 recyclerview 上顯示聊天項目。

如果我使用需要 position 的 notifyItemInserted() 方法,如何在 onChildAdded() 或 onChildChanged() 方法中獲取 position?

我的代碼如下:

val childEventListener = object : ChildEventListener {
        override fun onChildAdded(dataSnapshot: DataSnapshot, previousChildName: String?) {
            Log.d("MESSAGE", "onChildAdded:" + dataSnapshot.key!!)
            val message = dataSnapshot.getValue(Message::class.java)
            messageList.add(message!!)
            messageAdapter!!.notifyDataSetChanged()
        }

        override fun onChildChanged(dataSnapshot: DataSnapshot, previousChildName: String?) {
            Log.d("MESSAGE", "onChildChanged: ${dataSnapshot.key}")
        }

        override fun onChildRemoved(dataSnapshot: DataSnapshot) {
            Log.d("MESSAGE", "onChildRemoved:" + dataSnapshot.key!!)
        }

        override fun onChildMoved(dataSnapshot: DataSnapshot, previousChildName: String?) {
            Log.d("MESSAGE", "onChildMoved:" + dataSnapshot.key!!)
        }

        override fun onCancelled(databaseError: DatabaseError) {
            Log.w("MESSAGE", "messages:onCancelled", databaseError.toException())
        }
    }
    messagesDatabaseRef.orderByChild("createdAt").addChildEventListener(childEventListener)
}

要在回收器視圖中獲得更精細的更新(和動畫),您需要調用適配器上的notifyItemInsertednotifyItemChangednotifyItemMovednotifyItemRemoved方法,而不是notifyDataSetChanged 調用這些方法可為適配器提供此類更新所需的信息。

正如您所注意到的,您需要為這些調用指定位置,這意味着您必須保留從數據庫獲取的數據/快照到它們在視圖/適配器中占用的 position 的映射。

如果您想查看如何執行此操作的示例,請查看 FirebaseUI 庫中的FirebaseRecyclerAdapter class ,它的功能幾乎完全相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM