Well, thatโs what I found out.
I did not understand that all fragments associated with the activity when changing the configuration (turning the phone) are recreated and added to the activity. (which makes sense)
What happens in the TabListener constructor, the tab was detached if it was found and tied to activity. See below:
mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag); if (mFragment != null && !mFragment.isDetached()) { Log.d(TAG, "constructor: detaching fragment " + mTag); FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction(); ft.detach(mFragment); ft.commit(); }
Later in the onCreate action, the previously selected tab was selected from the state of the saved instance. See below:
if (savedInstanceState != null) { bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0)); Log.d(TAG, "FragmentTabs.onCreate tab: " + savedInstanceState.getInt("tab")); Log.d(TAG, "FragmentTabs.onCreate number: " + savedInstanceState.getInt("number")); }
When a tab has been selected, it will be reconnected in the onTabSelected callback.
public void onTabSelected(Tab tab, FragmentTransaction ft) { if (mFragment == null) { mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs); Log.d(TAG, "onTabSelected adding fragment " + mTag); ft.add(android.R.id.content, mFragment, mTag); } else { Log.d(TAG, "onTabSelected attaching fragment " + mTag); ft.attach(mFragment); } }
The attached snippet is the second call to the onCreateView and onActivityCreated methods. (The first is when the system recreates activity and all attached fragments). The first time the onSavedInstanceState Bundle package saved data, but not the second time.
The solution is to not separate the fragment in the TabListener constructor, just leave it attached. (You still need to find it in the FragmentManager tag by tag). Also in the onTabSelected method, I check if the fragment is detached before attaching it. Something like that:
public void onTabSelected(Tab tab, FragmentTransaction ft) { if (mFragment == null) { mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs); Log.d(TAG, "onTabSelected adding fragment " + mTag); ft.add(android.R.id.content, mFragment, mTag); } else { if(mFragment.isDetached()) { Log.d(TAG, "onTabSelected attaching fragment " + mTag); ft.attach(mFragment); } else { Log.d(TAG, "onTabSelected fragment already attached " + mTag); } } }