How to find a fragment that has been changed dynamically?

I have a layout with two Fragments in it. The second is loaded dynamically.

 Fragment fg = EmptyRightFrag.newInstance(); getFragmentManager().beginTransaction().add(R.id.right_frag, fg) .commit(); 

Then this second frame replaces another "fragment".

  Fragment fg = MyClass.newInstance(); getFragmentManager().beginTransaction().replace(R.id.right_frag, fg) .commit(); 

Finally, I need to initialize the second Fragment by calling:

 MyClass field = ((MyClass)getFragmentManager().findFragmentById(R.id.right_frag)); 

But here I get a java.lang.ClassCastException indicating EmptyRightFrag cannot be sent to MyClass .

+4
source share
2 answers

Where do you call findFragmentById() ? Immediately after you added it?

The docs for commit() say the following:

Schedules commit transaction. The end does not happen immediately; this will be planned, since work on the main thread will be the next time the thread is ready.

This means that Fragment will not be added for a while (at least until your method returns). In any case, you probably shouldn't handle initialization this way; it's better to leave the Fragment to take care of this in onCreate() or something like that.

+2
source

Just call getFragmentManager().executePendingTransactions(); to getFragmentManager().findFragmentById() and everything will be fine.

+2
source

All Articles