我有一个名为MainActivity的活动,里面有一个名为'HomeFragment'的片段。我希望在屏幕旋转后恢复片段,但似乎缺少某些东西。 我按照以下流程:
getSupportFragmentManager().putFragment(...)
onSaveInstanceState
保存片段
fragmentManager.findFragmentByTag
恢复片段(在检查该捆绑包不为空之后)但是findFragmentByTag
返回null。
以下是MainActivity中的代码段:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar to show a dropdown list.
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
setupNavigationSpinner(actionBar);
FragmentManager fragmentManager = getSupportFragmentManager();
if (savedInstanceState != null) {
if (fragmentManager.findFragmentByTag("frag") != null) {
// findFragmentByTag always return null
homeFragment = (HomeFragment) fragmentManager
.findFragmentByTag(HomeFragment.ARG_ITEM_ID);
contentFragment = homeFragment;
}else{
homeFragment = new HomeFragment();
switchContent(homeFragment, HomeFragment.ARG_ITEM_ID);
}
} else {
homeFragment = new HomeFragment();
switchContent(homeFragment, HomeFragment.ARG_ITEM_ID);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
getSupportFragmentManager().putFragment(outState, "frag",homeFragment );
}
public void switchContent(Fragment fragment, String tag) {
FragmentManager fragmentManager = getSupportFragmentManager();
while (fragmentManager.popBackStackImmediate())
;
if (fragment != null) {
FragmentTransaction transaction = fragmentManager
.beginTransaction();
transaction.replace(R.id.content_frame, fragment, tag);
// Only ArticlDetailFragment is added to the back stack.
if (!(fragment instanceof Fragment)) {
transaction.addToBackStack(tag);
}
transaction.commit();
contentFragment = fragment;
}
}
答案 0 :(得分:2)
没有理由打电话
getSupportFragmentManager().putFragment(outState, "frag",homeFragment );
将自动恢复Fragment
状态。问题是你没有打电话给onSaveInstanceState
的超级。它应该看起来像这样:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
此外,您将代码设置为HomeFragment.ARG_ITEM_ID
,然后查找"frag"
。是HomeFragment.ARG_ITEM_ID == "frag"
吗?