CicPot CicPot - 1 month ago 15
Android Question

adding multiple fragments programatically

I am using Fragment transaction to add two fragments to an activity. But it happens that only the first Fragment is shown when the app is started. Here is the code:

MainActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

FragOne firstButton = new FragOne();
FragmentTwo secButton = new FragmentTwo();

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

transaction.add(R.id.frag_container, firstButton);
transaction.add(R.id.frag_container, secButton);

transaction.commit();
}


activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:id="@+id/frag_container"
android:layout_height="fill_parent"
android:orientation="horizontal">

</LinearLayout>


frag_one.xml and frag_two.xml are similar

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button One" />
</LinearLayout>


So I am not sure what could be the problem ...I saw many examples with adding one fragment.

Answer

I'm not sure, but it's possible that both the fragment are actually added but because they are exactly the same and are located in a LinearLayout - one is hiding the other.

If i were you I would change the layout in the main activity to be a relative layout and add the fragment to two different place holder to check if this is the problem.

I haven't actually ran the program so it could be something else entirely... good luck!