getFragmentManager().beginTransaction()
.replace(R.id.graph_fragment_holder, new GraphFragment(), "GRAPH_FRAGMENT")
.commit();
getFragmentManager().beginTransaction()
.replace(R.id.list_fragment_holder, new ListFragment(), "LIST_FRAGMENT")
.commit();
//getFragmentManager().executePendingTransactions();
GraphFragment graphFragment = (GraphFragment) getFragmentManager().findFragmentByTag("GRAPH_FRAGMENT");
graphFragment.setData(data);
ListFragment listFragment = (ListFragment) getFragmentManager().findFragmentByTag("LIST_FRAGMENT");
listFragment.setData(data);
I've supplied a tag so I'm not sure why findFragmentByTag()
returns null
.
What I've tried from reading other questions:
this.setRetainInstance(true)
in theoncreate
of bothfragments
.Both
fragment
constructors are emptypublic fragmentName(){}
.tried
executePendingTransactions
after adding thefragments
.tried
add
instead ofreplace
on thefragments
(edited)
I was confused about this for a long time. First, you need to save the fragment you are replacing by pushing it onto the back stack. The tag you supply is put on the fragment you are adding, not the one you are pushing onto the back stack. Later, when you do push it onto the back stack, that tag goes with it. Here's code with objects broken out to make it easier to trace. You must call 'addToBackStack' before 'commit'.
Answered here, just need to call
getSupportFragmentManager().executePendingTransactions();
after your findByTag or findByIdYou can use
After that you can reuse it with
Call getFragmentManager().executePendingTransactions() after fragment transaction.
I was having the same problem of
findFragmentByTag()
always returning null.Eventually I tracked it down, I was overriding
onSaveInstanceState()
in my Activity but not calling super. As soon as I fixed thatfindFragmentByTag()
returned the Fragment as expected.In my case I had to create a class level FragmentManager object and then use it instead of using getSupportFragmentManager() directly.