[英]RecyclerView is empty when restoring fragment from backStack
我在Fragment中有一個RecyclerView
,最初是隱藏的。 當用戶單擊按鈕時,我將RecyclerView
可見性設置為true,並顯示ArrayList
上的一些數據。
當我將另一個片段移到頂部時,問題就開始了(我在backStack中添加了帶有RecyclerView
的上一個片段):如果我從新片段上單擊回來,則可以看到先前的片段(帶有RecyclerView
那個片段),並且在onCreateView()
記錄我用於recyclerView的dataSet的值,一切都在那里,但是recyclerView為空(僅顯示頁腳項)。
如果我們將RvFragment
稱為帶有RecyclerView
和NextFragment
的片段, NextFragment
該片段到達后堆棧然后離開架構為:
(back pressed)
RvFragment ----------> NextFragment ------------> RvFragment
這是onCreateView()
的代碼:
@Nullable
@Override
public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_photo_comments, container, false);
ButterKnife.bind(this, view);
Timber.i("onCreateView data.size == %d", commentArrayList.size());
setToolbarTitle();
Picasso.with(getActivity())
.load(photo)
.placeholder(R.drawable.ic_timeline_image_placeholder)
.centerCrop()
.fit()
.into(ivPhoto);
if (hasCommentsVisible) {
Timber.i("comments are visible!! and dataSize == %d", commentArrayList.size());
llFlagsCommentsContainer.setVisibility(View.GONE);
rvCommentsList.setVisibility(View.VISIBLE);
}
tvComments.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
hasCommentsVisible = true;
llFlagsCommentsContainer.setVisibility(View.GONE);
rvCommentsList.setVisibility(View.VISIBLE);
}
});
initRecyclerView();
return view;
}
您可以在上面的代碼中用log語句看到我可以確認數據存在。 謝謝!
我不確定我是否了解您如何設置片段堆棧,但是請確保:如果片段仍在堆棧上,則在您按返回按鈕時不會再次調用onCreateView。
https://developer.android.com/training/basics/fragments/fragment-ui.html#Replace
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
只有onStart()會。
如果您希望再次調用onCreateView,則需要使用
FragmentTransaction.replace(NextFragment)
沒有addToBackStack(),但這意味着整個片段將被重新創建。 可能不是您想要的,尤其是從Web服務獲取數據時。
另外,要在每次返回片段時完全重新創建片段,只需將其完全刪除即可:
FragmentTransaction.remove(RvFragment)
然后推下一個片段
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.