Android Add Fragment To Activity Dynamically Example

The fragment is widely used in android app development. You can use it statically or dynamically. Article Android Multiple Fragments In One Activity Example has introduced what it is and how to use Fragment statically. This article will tell you how to use it dynamically in your android app.

1. Dynamic Add Or Replace Fragment Steps.

  1. Get a android.support.v4.app.FragmentManager instance.
    FragmentManager fragmentManager = this.getSupportFragmentManager()
  2. Begin Fragment management transaction.
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
  3. Create a new Fragment instance.
  4. Call android.support.v4.app.FragmentTransaction‘s add(), remove() or replace() method to operate Fragment.
    fragmentTransaction.replace(R.id.dynamic_fragment_frame_layout, destFragment);
  5. Call the transaction object’s commit() method to commit the Fragment operation.
    fragmentTransaction.commit();

2. FragmentTransaction Methods.

  1. transaction.add() : Add a Fragment in current activity.
  2. transaction.remove() : Remove a Fragment from current activity. If the Fragment instance is not saved in Fragment back stack, then it will be destroyed.
  3. transaction.replace() : Use another Fragment to replace current Fragment.
  4. transaction.hide() : Hide current Fragment, only make it invisible, not destroy. Then you can show it later.
  5. transaction.show() : Make the hidden Fragment visible.
  6. transaction.detach() : Remove view objects from UI, but do not destroy it. The Fragment is still managed by Fragment Manager.
  7. transaction.attach() : Attach the view objects to UI.
  8. transaction.commit() : Commit a transaction. This method should be invoked before Activity.onSaveInstance(), otherwise, activity state loss error maybe occur.

3. Add Fragment To Activity Dynamically Example.

You can watch the youtube video https://youtu.be/bYbxB3oSJNI to see how this example behaves. There are 3 fragments ( android fragment, windows fragment, iOS fragment ) in this example.

Below are the source files of this example.

activity_dynamic_fragment.xml

This is the main activity layout XML file. It uses PercentFrameLayout. You can read the article Android PercentFrameLayout PercentRelativeLayout Example to learn more.

<android.support.percent.PercentFrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/dynamic_fragment_frame_layout"
        android:layout_gravity="top"
        app:layout_widthPercent="100%"
        app:layout_heightPercent="80%"/>


    <LinearLayout
        android:orientation="horizontal"
        android:layout_gravity="bottom"
        android:gravity="bottom"
        app:layout_widthPercent="100%"
        app:layout_heightPercent="20%">

        <Button
            android:id="@+id/dynamic_fragment_android_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Android"
            android:textSize="20dp"
            android:layout_weight="1"/>

        <Button
            android:id="@+id/dynamic_fragment_windows_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Windows"
            android:textSize="20dp"
            android:layout_weight="1"/>

        <Button
            android:id="@+id/dynamic_fragment_ios_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="iOS"
            android:textSize="20dp"
            android:layout_weight="1"/>

    </LinearLayout>
</android.support.percent.PercentFrameLayout>

fragment_dynamic_android.xml

This is the android fragment layout XML file.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="This is android fragment."
        android:textSize="60dp"
        android:textColor="@android:color/holo_red_light"
        android:gravity="center"/>

</LinearLayout>

fragment_dynamic_windows.xml

This is the windows fragment layout XML file.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="This is windows fragment."
        android:textSize="60dp"
        android:textColor="@android:color/holo_red_light"
        android:gravity="center"/>

</LinearLayout>

fragment_dynamic_ios.xml

This is the iOS fragment layout XML file.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="This is iOS fragment."
        android:textSize="60dp"
        android:textColor="@android:color/holo_red_light"
        android:gravity="center"/>

</LinearLayout>

DynamicFragmentActivity.java

This is the main activity java class.

package com.dev2qa.example.fragment.dynamic;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.dev2qa.example.R;

public class DynamicFragmentActivity extends AppCompatActivity {

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

        setTitle("dev2qa.com - Add Fragment Dynamically Example");

        // Create and set Android Fragment as default.
        Fragment androidFragment = new AndroidFragment();
        this.setDefaultFragment(androidFragment);

        // Click this button to display android fragment.
        Button androidButton = (Button)findViewById(R.id.dynamic_fragment_android_button);
        androidButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Fragment androidFragment = new AndroidFragment();
                replaceFragment(androidFragment);
            }
        });

        // Click this button to display windows fragment.
        Button windowsButton = (Button)findViewById(R.id.dynamic_fragment_windows_button);
        windowsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Fragment windowsFragment = new WindowsFragment();
                replaceFragment(windowsFragment);
            }
        });

        // Click this button to display iOS fragment.
        Button iosButton = (Button)findViewById(R.id.dynamic_fragment_ios_button);
        iosButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Fragment iosFragment = new IOSFragment();
                replaceFragment(iosFragment);
            }
        });

    }

    // This method is used to set the default fragment that will be shown.
    private void setDefaultFragment(Fragment defaultFragment)
    {
        this.replaceFragment(defaultFragment);
    }

    // Replace current Fragment with the destination Fragment.
    public void replaceFragment(Fragment destFragment)
    {
        // First get FragmentManager object.
        FragmentManager fragmentManager = this.getSupportFragmentManager();

        // Begin Fragment transaction.
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        // Replace the layout holder with the required Fragment object.
        fragmentTransaction.replace(R.id.dynamic_fragment_frame_layout, destFragment);

        // Commit the Fragment replace action.
        fragmentTransaction.commit();
    }

}

AndroidFragment.java

This is the android fragment implement class.

Please Note: The third parameter of the inflate method in the onCreateView override method must be false. Otherwise, it will throw the below error message.

Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child’s parent first.

package com.dev2qa.example.fragment.dynamic;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.dev2qa.example.R;

/**
 * Created by Jerry on 12/24/2017.
 */

public class AndroidFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // Please note the third parameter should be false, otherwise a java.lang.IllegalStateException maybe thrown.
        View retView = inflater.inflate(R.layout.fragment_dynamic_android, container, false);
        return retView;
    }
}

WindowsFragment.java

package com.dev2qa.example.fragment.dynamic;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.dev2qa.example.R;

/**
 * Created by Jerry on 12/24/2017.
 */

public class WindowsFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View retView = inflater.inflate(R.layout.fragment_dynamic_windows, container, false);
        return retView;
    }
}

IOSFragment.java

package com.dev2qa.example.fragment.dynamic;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.dev2qa.example.R;

/**
 * Created by Jerry on 12/24/2017.
 */

public class IOSFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View retView = inflater.inflate(R.layout.fragment_dynamic_ios, container, false);
        return retView;
    }
}

4. Question & Answer.

4.1 How to use FrameLayout to dynamically contain other fragments or activities.

  1. My android main activity’s layout is LinearLayout, it contains 3 buttons on the half-left side and a FrameLayout on the half-right side. The right side FrameLayout is an empty container, it will insert activities or fragments into the right side FrameLayout when clicking the buttons on the left side. How can I implement this? Thanks.
  2. Define a ViewGroup container in your activity, create an instance of your custom Fragment class. Then when the activity is active running, you can place the fragment object to the activity ViewGroup just like what this article said. You can add the below source code when the button is clicked.
    // Create an instance of the Fragment class.
    CustomFragment fragment = new CustomFragment();
    
    // Get the FragmentManager object.
    FragmentManager fragmentManager = getSupportFragmentManager()
    
    // Get the FragmentTransaction object.
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    
    // Place the fragment in the ViewGroup by the ViewGroup resource id.
    fragmentTransaction.add(R.id.activitycontent, fragment);
    
    // Commit the fragment transaction.
    fragmentTransaction.commit();
4.3 3 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Melvin
Melvin

In my android application, I do not want to use xml layout to insert the fragment to the main_activity.xml. I want to add the android fragment to the main activity in java source code like below.

WindowsFragment windowFragment = new WindowsFragment();

// First get FragmentManager object.
FragmentManager fragmentManager = this.getSupportFragmentManager();

// Begin Fragment transaction.
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

// Replace the layout holder with the required Fragment object. fragmentTransaction.add(R.id.dynamic_fragment_frame_layout, windowFragment);

// Commit the Fragment replace action.
fragmentTransaction.commit();

But when run the above source code it shows an alert with the error message application stopped. How can I fix it? Thanks.

TARZO
TARZO

AWESOME !!!

2
0
Would love your thoughts, please comment.x
()
x