The above heading was asked very often, but the answers seem to be closely related to FragmentStatePagerAdapter, which has nothing to do with my problem. I use the method directly putFragment(Bundle, String, Fragment).
Android documentation for putFragment(Bundle, String, Fragment)says:
Put a reference to a fragment in a Bundle. This Bundle can be persisted as saved state, and when later restoring getFragment(Bundle, String) will return the current instance of the same fragment.
Parameters
* bundle The bundle in which to put the fragment reference.
* key The name of the entry in the bundle.
* fragment The Fragment whose reference is to be stored.
However, the following code throws an exception:
Bundle bundle = new Bundle();
CustomFragment actionBarFragment = getActionBarFragment();
CustomFragment contentFragment = getContentFragment();
actionBarFragment.setArguments(bundle);
contentFragment.setArguments(bundle);
FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
mTransaction.add(R.id.actionBarPane, actionBarFragment);
mTransaction.add(R.id.contentPane, contentFragment);
mTransaction.commit();
getSupportFragmentManager().putFragment(bundle, "ContentFragment", contentFragment);
getSupportFragmentManager().putFragment(bundle, "ActionBar", actionBarFragment);
The reason I use the above is because both the ContentFragment fragment and the ActionBar can use the result getArguments()to find their opposite number, even if they are not currently at the top of the backstack - for example, if they are partially covered by the transparent fragments above on the stack.
However, I get an exception:
11-20 13:44:17.842: E/Default Exception Handler(12466): Caused by: java.lang.IllegalStateException: Fragment CustomFragment{4219bdb8 id=0x7f06002e com.test.CustomFragment1} is not currently in the FragmentManager
, commit() , putFragment() , ? - ? ( Android , , ).
commit(), , . , , , commit() ed. , ...
. ; , , .
EDIT
, commit() :
mTransaction.commit();
new Thread() {
public void run() {
while(!contentFragment.isAdded()) {
try {
Thread.sleep(100);
} catch (Exception e) {}
}
getSupportFragmentManager().putFragment(bundle, "ContentFragment", contentFragment);
getSupportFragmentManager().putFragment(bundle, "ActionBar", actionBarFragment);
};
}.start();
.