Double fragment rotating Android with ActionBar

后端 未结 4 721
轻奢々
轻奢々 2020-12-24 08:33

I\'ve made a simple Android Activity with an ActionBar to switch between 2 fragments. It\'s all ok until I rotate the device. In facts, when I rotate I\'ve got 2 fragment on

4条回答
  •  鱼传尺愫
    2020-12-24 08:49

    I've resolved using onSaveInstanceState and onRestoreInstanceState in the Activity to maintain the selected tab and modifying onTabSelected as follows.

    The last modify avoids that Android rebuild the Fragment it doesn't destoy. However I don't understand why the Activity is destroyed by the rotation event while the current Fragment no. (Have you some idea about this?)

    public void onTabSelected(Tab tab, FragmentTransaction ft) {
            // previous Fragment management
            Fragment prevFragment;
            FragmentManager fm = mActivity.getFragmentManager();
            prevFragment = fm.findFragmentByTag(mTag); 
            if (prevFragment != null) { 
                mFragment = prevFragment; 
            } // \previous Fragment management
    
            // Check if the fragment is already initialized
            if (mFragment == null) {
                // If not, instantiate and add it to the activity
                mFragment = Fragment.instantiate(mActivity, mClass.getName());
                ft.add(android.R.id.content, mFragment, mTag);
            } else {
                // If it exists, simply attach it in order to show it
                ft.attach(mFragment);
            }
        }
    

提交回复
热议问题