Android Multiple Fragments In One Activity Example

There are so many android devices in the world today. Different device screen sizes are also different. So when you create an android app, you must want it can be run in both small size ( android phone ) and big size ( android pad ) devices use only one release build.

For a small size android device ( android phone ), there are not so many spaces, so it will use only one panel to display content for different views ( title view, content view), each view can be implemented by one activity. But for big size android devices, the screen size is big, both the title list and the detailed content can be displayed in one panel only use one activity. How can we make the app to adapt both small size and big size android devices use only one activity? We can use android Fragments to implement this.

1. What Is Fragment.

  1. The fragment is something like Frame in Html. One Html can contain multiple Frames, and one Activity can include multiple Fragments.
  2. Each Fragment can have its own layout XML file, can contain its own view objects and encapsulate its own functionality. It can be reused by any activity.
  3. Each Fragment also has its own life cycle. Because Fragment depends on Activity. So Fragment life cycle is similar to the Activity life cycle.
  4. The below diagram illustrates the relationship between activity and fragment life cycle. We will introduce Fragment life cycle methods in another article later.
    android-fragment-life-cycle-diagram

2. Create A Tablet Emulator In Android Studio.

Because we will demo how to show multiple Fragments in one activity, so we need to use an Android tablet emulator. Below are the steps to create an android tablet emulator in android studio.

  1. Open android studio and click the Tools —> AVD Manager menu item in the android studio toolbar.
  2. Click the Create Virtual Device… button at the bottom left corner of the popup Android Virtual Device Manager window.
  3. Then it will popup the Virtual Device Configuration window.
  4. Click the Tablet item in the Category list panel, select the detail Tablet Name in the panel beside the Category list panel.
  5. Click the button Next —> Finish. Now you can see the newly created android tablet emulator in the android virtual device manager list.

3. Steps To Use Fragment.

  1. Create Fragment layout XML file, this layout XML file contains Fragment view controls.
  2. Create Fragment java class which extends android.support.v4.app.Fragment. And override its onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) method.
  3. Use the first parameter inflater to inflate the Fragment layout XML file and return the inflated view object.
  4. Use fragment XML tag to includes defined fragments in activity main layout XML file.

4. Communication Between Fragments And Activity.

  1. Fragment.getActivity() method can return a FragmentActivity object. This object is just the Fragment belongs Activity.
  2. FragmentActivity .getSupportFragmentManager() method will return a android.support.v4.app.FragmentManager instance.
  3. FragmentManager.findFragmentById() method can retrieve the desired Fragment object with specified id.
  4. Call Fragment.getView().findViewById() method to get the view controls in that Fragment.
  5. Then you can change the view control’s property and add an event listener.

4. Multiple Fragments In Activity Example.

 

This example includes two Fragments. Each Fragment has its own layout XML file and java class which extends android.support.v4.app.Fragment. The android.support.v4.app.Fragment class can make your Fragment compatible with the older android os version. You can watch the youtube video https://youtu.be/XSgzyiSORP8 to see the video demo.

fragment_left.xml

Left Fragment layout XML file, saved in app/res/layout folder. It contains three buttons.

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

    <Button
        android:id="@+id/fragmentLeftButtonAndroid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Android"
        android:textSize="20dp"
        android:textAllCaps="false"/>

    <Button
        android:id="@+id/fragmentLeftButtonIos"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="IOS"
        android:textSize="20dp"
        android:textAllCaps="false"/>

    <Button
        android:id="@+id/fragmentLeftButtonWindows"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Windows"
        android:textSize="20dp"
        android:textAllCaps="false"/>
</LinearLayout>

fragment_right.xml

Right Fragment layout XML file, saved in app/res/layout folder. It contains one TextView.

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

    <TextView
        android:id="@+id/fragmentRightTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="60dp"
        android:textColor="@android:color/holo_red_light"
        android:gravity="center"/>
</LinearLayout>

activity_multiple_fragment.xml

The activity layout XML file uses the fragment XML tag to include Fragments in the activity view.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <fragment
        android:id="@+id/fragmentLeft"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:name="com.dev2qa.example.fragmemt.multiple.FragmentLeft"/>

    <fragment
        android:id="@+id/fragmentRight"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:name="com.dev2qa.example.fragmemt.multiple.FragmentRight"/>
</LinearLayout>

FragmentLeft.java

Left Fragment implemented java class.

package com.dev2qa.example.fragmemt.multiple;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.dev2qa.example.R;

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

public class FragmentLeft extends Fragment {

    // This method will be invoked when the Fragment view object is created.
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View retView = inflater.inflate(R.layout.fragment_left, container);

        // Get Fragment belonged Activity
        final FragmentActivity fragmentBelongActivity = getActivity();

        if(retView!=null)
        {
            // Click this button will show the text in right fragment.
            Button androidButton = (Button)retView.findViewById(R.id.fragmentLeftButtonAndroid);
            androidButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    // Do not use fragmentBelongActivity.getFragmentManager() method which is not compatible with older android os version. .
                    FragmentManager fragmentManager = fragmentBelongActivity.getSupportFragmentManager();

                    // Get right Fragment object.
                    Fragment rightFragment = fragmentManager.findFragmentById(R.id.fragmentRight);

                    // Get the TextView object in right Fragment.
                    final TextView rightFragmentTextView = (TextView)rightFragment.getView().findViewById(R.id.fragmentRightTextView);

                    // Set text in right Fragment TextView.
                    rightFragmentTextView.setText("You click Android button.");
                }
            });


            // Click this button will show a Toast popup.
            Button iosButton = (Button)retView.findViewById(R.id.fragmentLeftButtonIos);
            iosButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(fragmentBelongActivity, "You click IOS button.", Toast.LENGTH_SHORT).show();
                }
            });


            // Click this button will show an alert dialog.
            Button windowsButton = (Button)retView.findViewById(R.id.fragmentLeftButtonWindows);
            windowsButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    AlertDialog alertDialog = new AlertDialog.Builder(fragmentBelongActivity).create();
                    alertDialog.setMessage("You click Windows button.");
                    alertDialog.show();
                }
            });
        }

        return retView;
    }
}

FragmentRight.java

Right Fragment implemented java class.

package com.dev2qa.example.fragmemt.multiple;

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 android.widget.TextView;

import com.dev2qa.example.R;

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

public class FragmentRight extends Fragment {

    // This method will be invoked when the Fragment view object is created.
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View retView = inflater.inflate(R.layout.fragment_right, container);

        if(retView!=null) {
            TextView fragmentRightTextView = (TextView)retView.findViewById(R.id.fragmentRightTextView);
            fragmentRightTextView.setText("This is the default right fragment.");
        }
        return retView;
    }
}

MultipleFragmentActivity.java

Main activity java file.

package com.dev2qa.example.fragmemt.multiple;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.dev2qa.example.R;

public class MultipleFragmentActivity extends AppCompatActivity {

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

        setTitle("dev2qa.com - Multiple Fragments In One Activity Example");
    }
}

6 thoughts on “Android Multiple Fragments In One Activity Example”

  1. Requirements:
    1. An Activity with two portions for fragments (do not use FragmentContainerView, instead use FrameLayout
    as you will be replacing fragments programatically).
    2. In the Left portion add ActionFragment that has two Buttons:
    Add Record
    Search Record
    3. In the right portion add MessageFragment that has a TextView that displays the following text: “Please
    select the appropriate action”
    4. Upon clicking Add Record button, MessageFragment in the right portion should be replaced by
    AddRecordFragment with following UI components: Email (EditText), Name (EditText), Age (EditText),
    Address (EditText), Save Record (Button)
    a. Upon clicking save record button following actions should be performed:
    i. The record must be saved in a Data Structure of your choice.
    You must make sure that this Data Structure be persisted throughout your
    app life.
    ii. After data is saved in Data Structure AddRecordFragment should be replaced by
    MessageFragment.
    5. Upon clicking Search Record button, SearchRecordFragment will replace MessageFragment with an
    EditText for getting an email address to search, and a TextView to display the searched record information.
    a. The search should be done on the managed Data Structure.

    Please help

  2. My android app has a sliding menu and I use this sliding menu to switch between three main fragments. In each main fragment, there is a button, when user press this button, it should start the main fragment’s child fragments in order. And it should also set the main fragment to the stack then user can go back to the main fragment later. I just want to use one main activity to switch between the 3 main fragments and manage the main fragment’s child fragments, how can I do this? Thanks.

    1. To implement what you need you should add a container in your application main activity XML file, then you can use the FragmentManager to replace the Fragment with multiple Fragments.

      Below is the main activity layout XML file.

      <?xml version=”1.0″ encoding=”utf-8″?>
      <FrameLayout xmlns:android=”http://schemas.android.com/apk/res/android”
      android:id=”@+id/fragmentContainer”
      android:layout_width=”match_parent”
      android:layout_height=”match_parent” >

      </FrameLayout>

      Below is the base activity class, it extends the Activity class and has a protected abstract method replaceContentFragment(). You can extend the base fragment activity class to create a sub-activity class for each of your fragments, and implement the replaceContentFragment() method to return each fragment content to the sub-activity class.

      public abstract class BaseFragmentActivity extends Activity {

      // Declare the replaceContentFragment method, the method can be override by the child activity class.
      protected Fragment replaceContentFragment();

      // This method will add the child fragment to the fragment container.
      private void addFragment() {

      // First get the FragmentManager object.
      FragmentManager fm = this.getFragmentManager();

      // Get the fragment container object.
      Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);

      // If there are no fragment in the fragment container.
      if (fragment == null) {

      // Get the target fragment object.
      fragment = this.replaceContentFragment();

      // Get the fragment transaction object.
      FragmentTransaction transaction = fragmentManager.beginTransaction();

      // Add the target fragment to the fragement container.
      transaction.add(R.id.fragmentContainer, fragment);

      // Commit the fragment transaction object.
      transaction.commit();
      }

      }
      }

  3. Really nice….but i need to change right side fragment with new fragment while clicking the button in left side fragment.How can i do it..??
    please help me.

    1. You can add an onclick listener to your button, and when the button is clicked you can execute the below source code in the button onclick listener method.

      // Get FragmentTransaction object.
      FragmentTransaction fragmentTransation = getFragmentManager().beginTransaction();

      // Replace the right fragment with the target fragment.
      fragmentTransation.replace(R.id.rightFragment, new TargetFragment(), “TargetFragmentTag”);

      // Do not forget to commit the fragment transaction to make the change effective.
      fragmentTransation.commit();

      // Below source code can make the app go back to the previous fragment when the user press the back button in the target fragment.
      fragmentTransation.addToBackStack(null)

Leave a Comment

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.

Clicky