I am using a LinearLayout with a vertical orientation to list fragments. I add fragments to the container programmatically like this:
FragmentTransaction ft = fragmentManager.beginTransaction();
Fragment fragment1 = new Fragment();
ft.add(R.id.llContainer, fragment1);
Fragment fragment2 = new Fragment();
ft.add(R.id.llContainer, fragment2);
ft.commit();
But it only shows the first fragment. Why?
You can have multiple fragments in a LinearLayout
.
According to the documentation,
If you're adding multiple fragments to the same container, then the order in which you add them determines the order they appear in the view hierarchy
The problem with your code is that because you didn't specify fragment tags, it defaulted to the container id. Since the container id is the same for both transactions, the 2nd transaction replaced the 1st fragment, rather than added it to the container separately.
To do what you want, use something like:
FragmentTransaction ft = fragmentManager.beginTransaction();
Fragment fragment1 = new Fragment();
ft.add(R.id.llContainer, fragment1, "fragment_one");
Fragment fragment2 = new Fragment();
ft.add(R.id.llContainer, fragment2, "fragment_two");
ft.commit();