Skip to content Skip to sidebar Skip to footer

Cannot Add Multiple Fragments To Linearlayout

I am using a LinearLayout with a vertical orientation to list fragments. I add fragments to the container programmatically like this: FragmentTransaction ft = fragmentManager.begin

Solution 1:

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:

FragmentTransactionft= fragmentManager.beginTransaction();

Fragmentfragment1=newFragment();
ft.add(R.id.llContainer, fragment1, "fragment_one");

Fragmentfragment2=newFragment();
ft.add(R.id.llContainer, fragment2, "fragment_two");

ft.commit();

Solution 2:

Had the same problem, but using

@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Viewview= inflater.inflate(R.layout.control_list, container, false);

I.E. using a xml layout file:

<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"android:id="@+id/control_list"></LinearLayout>

Solved my problem. When creating the LinearList programmatically only the first fragment showed up for me too.

That is using an xml file for the layout you want to add the fragments to.

Solution 3:

solved it by adding this to the linearlayout:

android:orientation="vertical"

Post a Comment for "Cannot Add Multiple Fragments To Linearlayout"