user645402
user645402

Reputation: 837

fragments and screen orientation changes

i do not understand how fragments and screen orientation is supposed to work in android.

I have a fragment defined in XML.

The fragment is expensive to create, so i want to re-use it.

I have code that looks like this:

@Override
protected void onSaveInstanceState (Bundle outState) {
    super.onSaveInstanceState(outState);
    getSupportFragmentManager().putFragment(outState, "myfrag", mFrag);
}

and

@Override
protected void onRestoreInstanceState (Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    mFrag = getSupportFragmentManager().getFragment(savedInstanceState, "myfrag");
}

What I don't understand is how to replace the fragment in XML with the fragment I've re-obtained. When i do a screen orientation change, it winds up destroying my activity and re-creating it, but if I can save my fragment and reuse it, it should make orientation changes a lot faster.

tia.

Upvotes: 0

Views: 3969

Answers (1)

Bram
Bram

Reputation: 4613

You could create a framelayout in xml and a fragment in code. Then add the created fragment to your framelayout. On orientation change you try to find your created fragment by use of a tag or id and do some remove / add actions.

fragmentmanager.findFragmentByTag(" ... ");
fragmentmanager.add(R.id.fragmentContainer, myFragment, "...");

Something like that.

http://developer.android.com/guide/topics/fundamentals/fragments.html Take a look at the sub-section "Or, programmatically add the fragment to an existing ViewGroup". This is a sub-section of the section "Adding a fragment to an activity".

Kind regards, Bram

Upvotes: 1

Related Questions