我有一個名爲MainActivity的活動,裏面有一個名爲「HomeFragment」的片段。我想在屏幕旋轉後恢復片段,但有些東西似乎丟失了。 我採取了以下過程:Android旋轉:爲什麼片段不能被TAG恢復?
- 節省使用
getSupportFragmentManager().putFragment(...)
片段中onSaveInstanceState
- 嘗試通過
fragmentManager.findFragmentByTag
的onCreate期間恢復片段(檢查包後不爲空)
然而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;
}
}
由於某種原因,我遇到了同樣的問題。 – 2014-10-04 12:53:29
呃......你可能想向我們展示'switchContent'中發生了什麼。 – 2014-10-04 14:01:49
@PaulBurke更新 – VSB 2014-10-04 14:03:18