Android Multiple Fragments In One Activity Example

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

For small size android device ( android phone ), there are not so many spaces, so it will use only one panel to display content for different view ( title view, content view), each view can be implemented by one activity.

android phone app multiple activity single panel

But for big size android devices, the screen size is big, both title list and the detail content can be displayed in one panel only use one activity.

android pad app one activity show multiple view

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.

Fragment is something like Frame in Html. One Html can contains multiple Frames, and one Activity can includes multiple Fragments.

Each Fragment can has it’s own layout xml file. Contains it’s own view objects and encapsulate it’s own functionality. It can be reused by any activity.

Each Fragment also has it’s own life cycle. Because Fragment depends on Activity. So Fragment life cycle is similar to Activity life cycle.

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 is the steps to create android Tablet emulator in android studio.

  1. Click the AVD Manager button in android studio tool bar.
    avd manager in the tool bar
  2. Click Create Virtual Device… button in the popup android virtual device manager window.
    android virtual device list manager
  3. Select Tablet and detail Tablet Name in left panel, click Next and Finish. Now you can see the newly created android tablet emulator in the android virtual device manager list.
    android virtual device manager create tablet
READ :   Android Layer-List Example

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 it’s 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 event listener.

4. Multiple Fragments In Activity Example.

 

android multiple fragments in one activity example release

This example includes two Fragments. Each Fragment has it’s own layout xml file and java class which extends android.support.v4.app.Fragment. 

android.support.v4.app.Fragment can make your Fragment compatible with older android os version.

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

This the activity layout xml file, it use 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");
    }
}
(Visited 20,847 times, 9 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.