Jarvis Millan Jarvis Millan - 5 months ago 18
Android Question

Android Handling orientation changes - no change if rotation occurs

i have a problem dealing with orientation.

i have a fragment in an activity that loads when i run the app.

fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, new HomeFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Home");


Output:(default orientation - portrait)

enter image description here

but when i rotate the phone into landscape, it just adds up the fragment.

Output :

enter image description here

is there any way that i can fix this? I've been reading some questions about dealing rotations on run time, but their solutions are to disable the orientation. Some also say that to use AsyncTask functions on dealing with this matter. I am new on android and i am not yet familiar to other android libraries. thanks for answering.

Answer

The screen rotation will not destroy your previous fragment, instead saving and restoring it's state.

I'm guessing you call that fragmentTransaction logic inside your Activity's onCreate method, so each time the activity is restored it is adding a new fragment on top of the old one(s).

You can prevent this by checking if the savedInstanceState Bundle is null on your onCreate() method, that way you won't add a new fragment if your activity is being recreated like so:

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    ...

    if(savedInstanceState == null) {
        fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.main_container, new HomeFragment());
        fragmentTransaction.commit();
        getSupportActionBar().setTitle("Home");
    }

}

Hope it helps.

Comments