我有一个Activity,其中包含许多基于导航抽屉中所选项目交换的片段。我试图通过调用Fragment上的setRetainInstance(true)
来检查方向更改中的当前片段,然后检查onCreate(...)
中是否存在该片段。但是,当我尝试在onCreate(...)
上获取时,Fragment始终为null。我一直在我的桌子上撞了几个小时。有人能发现问题吗?
活动的相关部分
public class StartActivity {
private static final String MAIN_FRAGMENT_TAG = "mainFragment";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
...
if(savedInstanceState != null) {
Fragment f = getSupportFragmentManager().findFragmentByTag(MAIN_FRAGMENT_TAG);
if(f == null) {
// FRAGMENT IS ALWAYS NULL
switchToModeForPosition(...);
} else {
setupActionBarForPosition(...);
}
} else {
// Default to events view
switchToModeForPosition(0);
}
}
private void switchToModeForPosition(int position) {
Fragment fragment;
switch (position) {
default:
case 0: //events
fragment = new EventsByWeekFragment();
setupActionBarForEvents();
break;
case 1: //teams
fragment = new AllTeamsListFragment();
setupActionBarForTeams();
break;
case 2: //insights
fragment = new InsightsFragment();
setupActionBarForInsights();
break;
case 3:
startActivity(new Intent(this, SettingsActivity.class));
mDrawerLayout.closeDrawer(mDrawerList);
return;
}
fragment.setRetainInstance(true);
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment, MAIN_FRAGMENT_TAG).commit();
}
}
答案 0 :(得分:0)
在每个setRetainInstance(true)
课程中使用Fragment
。
public void onCreated(Bundle savedInstanceState)
{
super.onCreated(savedInstanceState);
setRetainInstance(true);
}
或
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}