Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment recreation on configuration change

I have a doubt on configuration change handling by os, Lets say I have an Activity inside its onCreate() it is creating one (or more) fragment instance using a special constructor defined in that fragment.

When device orientation changes system will destroy and create the fragment again, if I am correct it will use default (no argument) constructor to do that, meanwhile the activity is also getting recreated and it will again instantiate fragment using same constructor. My question is, will there be two different instances in the memory? if not, how they are resolved and become one?

like image 672
duckduckgo Avatar asked Jan 18 '16 13:01

duckduckgo


1 Answers

Some background

The responsibility to keep the state of a fragment throughout the life of the activity is on the FragmentManager, this is why there is an option to commit and to commitAllowingStateLoss when committing a fragment transaction. If left to it's own devices the Fragment's state will be restored automatically. But... if you add the fragment in code (as opposed to adding it in the xml layout) then it is up to you to add it only when needed.
Usually, in the case of onCreate it is enough to check that the activity is not being restarted, that is, check that savedInstanceState == null and only then add the fragment.

Take a look at this snippet from the fragment's guide:

public static class DetailsActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getResources().getConfiguration().orientation
            == Configuration.ORIENTATION_LANDSCAPE) {
        // If the screen is now in landscape mode, we can show the
        // dialog in-line with the list so we don't need this activity.
        finish();
        return;
    }

    if (savedInstanceState == null) {
        // During initial setup, plug in the details fragment.
        DetailsFragment details = new DetailsFragment();
        details.setArguments(getIntent().getExtras());
        getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
    }
}

}

P.S.

The answer to your question:

will there be two different instances in the memory?

Yes, if you just add the fragment on each call to onCreate there will be more than one instance.

like image 187
Alex.F Avatar answered Oct 08 '22 20:10

Alex.F