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");
    }
}
0 0 votes
Article Rating
Subscribe
Notify of
guest

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

5 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Justin
Justin

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.

Divya
Divya

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.

Bapu Darbar
Bapu Darbar
Reply to  Divya

An Easily You Change That Code , And New Effective
Thanks ,

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