I found many post explaining how get the Fragment
from the savedInstanceState
Bundle
but, because the Activity
can swap between 4 Fragments
, i need a way to know which Fragment was alive before rotate when the orientation started to change.
The reason i have several Fragments is because i am using Navigation Drawer, so each menu item as a fragment.
Fragments — Scenario 3: Activity with retained Fragment is rotated. The fragment is not destroyed nor created after the rotation because the same fragment instance is used after the activity is recreated. The state bundle is still available in onActivityCreated .
Yes you can, but you have to add more logic to your fragments and add some interfaces for each activity.
Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.
At runtime, a FragmentManager can add, remove, replace, and perform other actions with fragments in response to user interaction. Each set of fragment changes that you commit is called a transaction, and you can specify what to do inside the transaction using the APIs provided by the FragmentTransaction class.
I had the same issue and I fixed it adding this to the Navigation Drawer activity code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState==null){
//Handle the initial fragment transaction
}
...
}
For example, I have a navigation drawer with "Home", "Settings" and "About" as menu items, each with a fragment "home_fragment", "settings_fragment" and "about_fragment".
If I want "home_fragment" to appear when the navigation drawer activity launches, I use this code on the OnCreate function:
FragmentManager fM = getSupportFragmentManager();
fM.beginTransaction().replace(R.id.NavDrawContent,new home_fragment()).commit();
But I want it to execute only when (savedInstanceState == null), so that when we change the phone orientation while in settings_fragment (for example), it doesn't inflate home_fragment.
So the final code (inside the navigation drawer activity OnCreate):
super.onCreate(savedInstanceState);
if(savedInstanceState==null){
FragmentManager fM = getSupportFragmentManager();
fM.beginTransaction().replace(R.id.NavDrawContent,new home_fragment()).commit();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With