Android轮换:为什么片段没有被TAG恢复?

时间:2014-10-04 12:41:55

标签: android android-fragments screen-rotation onrestoreinstancestate

我有一个名为MainActivity的活动,里面有一个名为'HomeFragment'的片段。我希望在屏幕旋转后恢复片段,但似乎缺少某些东西。 我按照以下流程:

  1. getSupportFragmentManager().putFragment(...)
  2. 期间使用onSaveInstanceState保存片段
  3. 尝试在onCreate期间通过fragmentManager.findFragmentByTag恢复片段(在检查该捆绑包不为空之后)
  4. 但是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;
        }
    }
    

1 个答案:

答案 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"吗?