4ndro1d
4ndro1d

Reputation: 2976

Android replace Fragment

My MainActivity contains 2 fragments. The upper one contains a map and should be visible all the time. The lower one should initially show a ListView and on FAB clicked it should change to a Fragment, in which it is possible to add a new entry.

enter image description here

I tried to run the following code in my MainActivity on button click:

    AddFragment newFragment = new AddFragment();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    transaction.replace(R.id.fragment_container, newFragment);
    transaction.addToBackStack(null);
    transaction.commit();
    getSupportFragmentManager().executePendingTransactions();

But nothing is happening at all.

Here is my XML:

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="2" />


    <LinearLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">

        <fragment
            android:id="@+id/frag_list"
            android:name="com.example.imissit.ListFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>
</LinearLayout>

Upvotes: 0

Views: 525

Answers (1)

mbelsky
mbelsky

Reputation: 6618

Remove the fragment tag from xml file, and add the ListFragment programmatically, f.e.:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(…);
    if ( null == savedInstanceState ) {
        getSupportFragmentManager().beginTransaction()
                .replace(CONTAINER_ID, FRAGMENT_INSTANCE, TAG) // Change the values
                .commit();
    }
}

Also change LinearLayout to FrameLayout

Upvotes: 2

Related Questions