I have a layout with two Fragments in it. Second one loads dynamically.
Fragment fg = EmptyRightFrag.newInstance();
getFragmentManager().beginTransaction().add(R.id.right_frag, fg)
.commit();
Then this second frame replaces with 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 do get java.lang.ClassCastException stating EmptyRightFrag cannot be casted to MyClass.
Where are you calling
findFragmentById()? Directly after you added it?The docs for
commit()says this:This means that the
Fragmentwill not be added for a while (at least not before your method has returned). Anyways you should probably not handle initialization this way, it’s better to let the Fragment take care of that inonCreate()or something.