如何正确使用片段 [英] How to correctly using fragments
问题描述
在我的基类的活动我有联系,我从菜单中调用所有片段。
In my base Activity class I have links to all fragments that I call from menu.
事情是这样的:
BaseFragment mProjects;
BaseFragment mProfile;
public BaseFragment getFragment(FragmentType type) {
BaseFragment fr = null;
switch (type) {
case PROFILE:
fr = new Profile();
break;
case PROJECTS:
fr = new Projects();
break;
default:
return null;
}
return fr;
}
所以,我创建片段从菜单有一次,访问的实例。好吗?或者我应该创建片段每次?如果是这样,那我怎么才能救片段的状态(数据位)?因为当我使用替换
从片段经理,的onSaveInstanceState
替换片段不叫。所以,当我将重新打开它,没有保存的状态。
So, i create instance of fragments that accessible from menu one time. Is it good? Or i should create fragment every time? If so, then how can i save state of fragment (data, position)? Cause when i use replace
from fragment manager, onSaveInstanceState
of replaced fragment doesn't called. So when i will reopen it, there is no saved state.
顺便说一句,我使用的onSaveInstanceState
的活动:
Btw, I'm using onSaveInstanceState
in Activity:
@Override
public void onSaveInstanceState(Bundle saveInstanceState) {
// doing things
super.onSaveInstanceState(saveInstanceState);
}
无论如何,如果我不存储链接片段的onSaveInstanceState
片段将永远不会被调用。所以,我可以存储片段的状态的onPause
方法,但似乎不好解决。
Anyway if i don't store links to fragments onSaveInstanceState
of fragment will never called. So, i can store state of fragment in onPause
method, but it seems bad solution.
UPD:它不是基于观点的问题。应该有使用片段的最佳做法。所以我要求这一点。
UPD: it's not opinion based question. There should be best practice for using fragment. So i asked for this.
推荐答案
在您更换当前显示的片段,需要 getSupportFragmentManager()。putFragment(束,弦乐,片段)
,这将存储片段成束,你可以保持一个参考,并保存到您的活动的实例状态。
Before you replace a currently shown fragment, you need to getSupportFragmentManager().putFragment(Bundle, String, Fragment)
, this will store that fragment into a Bundle which you can keep a reference to, and save to your activity's instance state.
在你的 getFragment
方法,首先查看,如果你一直保存碎片进入包包含你要创建的片段 - getSupportFragmentManager ().getFragment(捆绑,字符串)
。这会给你,你可以返回并更换一个片段。如果没有,创建片段的新实例,你目前是。
In your getFragment
method, first check to see if the bundle you have been saving your fragments into contains the fragment you want to create - getSupportFragmentManager().getFragment(Bundle, String)
. This will give you a fragment you can return and replace. If not, create a new instance of the fragment as you currently are.
这篇关于如何正确使用片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!