首頁 > Java > java教程 > 主體

如何使用 FirebaseUI-Android 管理 RecyclerView Item ViewHolders 中的事件偵聽器?

Mary-Kate Olsen
發布: 2024-10-26 15:25:03
原創
446 人瀏覽過

How to Manage Event Listeners in RecyclerView Item ViewHolders with FirebaseUI-Android?

如何使用FirebaseUI-Android 函式庫在RecyclerView Item ViewHolder 中新增和移除事件監聽器

在本文中,我們將指導您如何使用 addSnapshotListener 並在不需要時將其刪除RecyclerView 適配器的 populateViewHolder 方法。

populateViewHolder 方法

populateViewHolder 方法是將 Firebase 快照中的資料綁定到 ViewHolder 的地方。要檢索引用的數據,請使用以下方法:

<code class="java">@Override
protected void populateViewHolder(final ConvViewHolder convViewHolder, final Conv conv, int i) {

    final String list_user_id = getRef(i).getKey();

    final DocumentReference docRef = db.collection("cities").document(list_user_id);
    // Add a listener to the document reference
    EventListener<DocumentSnapshot> eventListener = new EventListener<DocumentSnapshot>() {
        @Override
        public void onEvent(@Nullable DocumentSnapshot snapshot,
                            @Nullable FirebaseFirestoreException e) {
            if (e != null) {
                Log.w(TAG, "Listen failed.", e);
                return;
            }

            if (snapshot != null && snapshot.exists()) {
                Log.d(TAG, "Current data: " + snapshot.getData());
            } else {
                Log.d(TAG, "Current data: null");
            }
        }
    };
    docRef.addSnapshotListener(eventListener);
}</code>
登入後複製

分離事件監聽器

當不再需要數據時,分離監聽器非常重要避免不必要的頻寬消耗。為此,請聲明一個全域ListenerRegistration 變量,並僅在需要時新增偵聽器,如下所示:

<code class="java">// Inside your RecyclerView adapter
private ListenerRegistration listenerRegistration;

if (listenerRegistration == null) {
    listenerRegistration = yourRef.addSnapshotListener(eventListener);
}</code>
登入後複製
並在onStop() 方法中刪除偵聽器:

<code class="java">@Override
protected void onStop() {
    if (listenerRegistration != null) {
        listenerRegistration.remove();
    }
}</code>
登入後複製

其他注意事項

    如果您只需要讀取一次文檔,請考慮使用get() 方法而不是addSnapshotListener。
  • 您也可以將 Activity 傳遞為addSnapshotListener 中的第一個參數讓 Firestore 在活動停止時自動清理偵聽器。

以上是如何使用 FirebaseUI-Android 管理 RecyclerView Item ViewHolders 中的事件偵聽器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!