HomeAndroidHow to Add a Fragment to an Activity at Runtime in Android...

How to Add a Fragment to an Activity at Runtime in Android App?

Rather than defining the fragments for an activity in the layout fileĀ with theĀ <fragment>Ā elementā€”you can add a fragment to an activity at runtime in Android app. This is necessary if you plan to change fragments during the life of the activity.

To perform a transaction such as add or remove a fragment, you must use theĀ FragmentManagerĀ to create aĀ FragmentTransaction, which provides APIs to add, remove, replace, and perform other fragment transactions.

If your activity allows the fragments to be removed and replaced, you should add the initial fragment(s) to the activity during the activity’sĀ onCreate()method.

An important rule when dealing with fragmentsā€”especially when adding fragments at runtimeā€”is that your activity layout must include a containerĀ ViewĀ in which you can insert the fragment.

The following layout includes an emptyĀ FrameLayoutĀ that acts as the fragment container.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:id="@+id/fragment_container" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" />

Inside your activity, callĀ getSupportFragmentManager()Ā to get aĀ FragmentManagerĀ using the Support Library APIs. Then callĀ beginTransaction()to create aĀ FragmentTransactionĀ and callĀ add()Ā to add a fragment.

You can perform multiple fragment transaction for the activity using the sameĀ FragmentTransaction. When you’re ready to make the changes, you must callĀ commit().

For example, here’s how to add a fragment at runtime to the Activity:

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class MainActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_articles);

        // Check that the activity is using the layout version with
        // the fragment_container FrameLayout
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            // Create a new Fragment to be placed in the activity layout
            HeadlinesFragment firstFragment = new HeadlinesFragment();

            // In case this activity was started with special instructions from an
            // Intent, pass the Intent's extras to the fragment as arguments
            firstFragment.setArguments(getIntent().getExtras());

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, firstFragment).commit();
        }
    }
}

Because the fragment has been added to theĀ FrameLayoutĀ container at runtimeā€”instead of defining it in the activity’s layout with aĀ <fragment>elementā€”the activity can remove the fragment and replace it with a different one.

RELATED ARTICLES

Most Popular