Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment overlaps on activity rotation

I'm getting really confused about this. I have an actionbar with list navigation. I click on the list to open 2 fragment one after another and display in the same activity. I'm basically replacing them using this method:

public void openFragment(AprilAppsFragment createdFragment){        
    if (createdFragment.getClass().isInstance(getDisplayedFragment()))
        return;

    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

    transaction.replace( R.id.main_fragment, createdFragment, "displayed fragment"); 
    transaction.addToBackStack(null);
    transaction.commit();  
}

I open fragment A, then I open fragment B, then I rotate the screen. Fragment A is being recreated crashing my app

Whys is that, since I'm using replace? How do I avoid recreating fragments that no longer being shown, without losing possibility of back-pressing to them?

like image 335
Jacek Kwiecień Avatar asked Dec 06 '22 09:12

Jacek Kwiecień


2 Answers

Your problem is that you are not saving state for your fragments, and since you haven't added

android:configChanges="orientation|screenSize"

your first fragment is called again, and since you have no saved state your app crashes. So its good that you add the line above in you Activity declaration in the manifest like:

<activity android:name=".yourActivity" android:configChanges="orientation|screenSize"

and Override the onSaveInstanceState and save states for both your fragments. And in your onCreate just do this check:

if(savedInstanceState != null){
fragmentA = (FragmentA) fragmentManager.getFragment(savedInstanceState, stringValueA);
fragmentB = (FragmentB) fragmentManager.getFragment(savedInstanceState, stringValueB);
}

And then check if any of your fragment is not null than create its instance and set that to fragmentTransaction.relplace. Or do this in your for openFragment method.

Cheers,

like image 130
AliR Avatar answered Dec 19 '22 23:12

AliR


Fragments save their state (and the location on the back stack) automatically on rotation. Make sure you aren't recreating your fragments or calling openFragment in your onActivityCreated or onCreate methods.

like image 35
ianhanniballake Avatar answered Dec 20 '22 00:12

ianhanniballake