Android Add Fragment To Activity Dynamically Example

Fragment is widely used in android app development. You can use it statically or dynamically. Article Android Multiple Fragments In One Activity Example has introduce what 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 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.

android add fragment to activity dynamically example

activity_dynamic_fragment.xml

This is the main activity layout xml file. It use PercentFrameLayout. You can read 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 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 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 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 android fragment implement class.

READ :   How To Add Activity In Android Studio

Please Note : The third parameter of the inflate method in onCreateView override method must be false. Otherwise it will throw 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.

android fragment illegal state exception

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;
    }
}
(Visited 4,498 times, 53 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

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