I am creating a Fragment FragParent displaying several input-fields, one of which is a sub-Fragment frag, with specialized audio controls.
The layouts of both fragments are loaded from XML in their onCreateView() methods.
Code I am using is below, but I have some questions about it:
A) is it OK to replace() the sub-Fragment if it is already returned by findFragmentByTag(), or is that an unnecessary step?
B) can the sub-Fragment be instantiated and replaced in the layout, before the parent Fragment completes the inflate() call?
<!-- language: lang-java -->
// Load sub-Fragment with audio UI.
String fragStr = "fragment_audio_str";
int fragView = R.id.frag_audio_frame_layout;
FragmentManager fm = getChildFragmentManager();
FragmentTransaction fmt = fm.beginTransaction();
Fragment frag = (Fragment) fm.findFragmentByTag(fragStr);
if (null == frag) {
frag = new Fragment();
}
fmt.replace(fragView, frag, fragStr);
fmt.commit();
return inflater.inflate(R.layout.fragment_parent, container, false);
} // END onCreateView() of FragParent
No, it shouldn’t be necessary to replace the fragment if it is already there. However you need to replace your child fragment if it isn’t there.
No, you need to inflate the parent
Fragmentlayout and then add your childFragmentto it before returning the parent’sView.Try something like this: