James Cross
James Cross

Reputation: 7879

Nested fragments on configuration (orientation) change

I am having trouble understanding how Android deals with fragments (particularly nested fragments) on an orientation change.

Say I have an activity a1 that loads a fragment f1. f1 then loads multiple instances of fragment f2 into itself in the oncreateview() method.

Now my activity a1 has this in (oncreate()):

if (savedInstanceState != null)
    return;

to make sure that multiple instance of f1 don't get loaded. I do the same sort of thing in f1 to makes sure duplicate f2 instances don't get loaded.

However, my class f1 needs to reference the f2 instances later on. Currently I am storing them in an ArrayList in the f1 object, however after an orientation change this ArrayList is empty and I think the f2 instances will be different objects any way.

So my question is, how is the best way to have nested fragments and to keep a reference to them after an orientation change?

Upvotes: 2

Views: 2233

Answers (1)

Scott Naef
Scott Naef

Reputation: 177

You can use FragmentManger to find references to other fragments.

You can an get a reference to another fragment by doing something like:

DetailsFragment details = (DetailsFragment) getFragmentManager().findFragmentById(R.id.details);

or

DetailsFragment details = (DetailsFragment) getFragmentManager().findFragmentByTag("my tag");

If you have not already seen it take a look at this blog post.

In your case where you have multiple instances of the same fragment you can set a tag when you create the fragment and use that instead of the id when looking for the fragment.

Upvotes: 2

Related Questions