Where does android add fragment when I call FragmentTransaction add (Fragment fragment, String tag)
I have written this code, but I can't see fragment's layout. It displays an empty screen.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Fragment fragment = new TestFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(fragment, "test");
ft.commit();
} // onCreate
public class TestFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag_layout, container, false);
}
} // TestFragment
You need to specify layout resource ID
so, the FragmentTransaction
can add your fragment to that resource (container).
When you call FragmentTransaction.add(Fragment, Tag)
you actually calling FragmentTransaction.add(0,Fragment,Tag)
and keep in mind "0" is not a valid resource ID. So actually your fragment is created without any view.
It is possible to have fragments without the view so this method actually is used for those types of fragments which just created to do some processing but have no interactions with layouts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With