Reputation: 11
I'm trying to replace the fragment in a container.
For the visual stuff I can see a change and the new fragment get initialized.
But if I check, which object in the container is, it still gives me the old fragment i replace before, the leads to the problem, that i can't call a method of the new fragment because it didn't got replaced to 100%.
Here my code:
fragmentTransaction = getFragmentManager().beginTransaction();
Volumefragment volumefragment = new Volumefragment();
System.out.println("Change Fragment");
fragmentTransaction.replace(R.id.framecontainer,volumefragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
if(getFragmentManager().findFragmentById(R.id.framecontainer) instanceof Dummyfragmenet){
System.out.println("Wrong object");
}
}
Upvotes: 1
Views: 41
Reputation: 31
When you do a commit with the Fragment transaction, what you are really doing is scheduling the replacement of that fragment. It won't happen immediately, and it will be replaced when the UI thread gets ready to do it. So your printing is being called when the fragment transaction is not fully completed (Since it is happening asynchronously). If you want to make sure that the fragment has been replaced, right after the commit and before the printing, add the following:
getFragmentManager().executePendingTransactions()
To clarify, and taken from the documentation "After a FragmentTransaction is committed with FragmentTransaction.commit(), it is scheduled to be executed asynchronously on the process's main thread." Visit https://developer.android.com/reference/android/app/FragmentManager.html#executePendingTransactions()
Upvotes: 3