[英]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.