1. 程式人生 > 其它 >Android 解決Fragment內的RecyclerView重建後內容不顯示

Android 解決Fragment內的RecyclerView重建後內容不顯示

佈局

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rvContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
        app:spanCount="4"
        tools:listitem="@layout/item_gallery_scanning" />

</androidx.constraintlayout.widget.ConstraintLayout>

當重建或回到手機主頁再返回至app時,資料不再顯示,原因是資料載入在了未銷燬的前一個fragment裡面,然後被銷燬了,而新建的fragment無資料。

  • 解決方法
    在RecyclerView渲染完成後再載入資料
rvContent.post(() -> {
            if(albumMediaCollection!=null)
                albumMediaCollection.load(imageFolder);
        });