Android Fragment Communication With Activity Example

This example shows you how to communicate between android fragment and activity and how to transfer data between different fragments in the android application.

1. Communication Between Android Fragments And Activity.

  1. Because android-fragments usually be placed in activity’s layout XML or dynamically created in activity’s source code, so if you want to pass data from activity to fragment, you can just invoke the fragment’s method directly in the android activity code.
  2. If you want the fragment to pass data to related activity, you can follow the below steps.
  3. Define an interface which contains methods that fragment wants the activity to override.
  4. Make the activity implement the above interface and override the methods declared in it.
  5. When the fragment’s onAttach(Context context) method is invoked by android os during activity load the fragment, assign the context input parameter to one fragment’s instance variable, the context variable just refer to the activity. Then you can call the activity method in the fragment.

2. Fragments Communication In Activity Example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/kgWEgP6koTc

  1. There are three fragments in this example. An up-fragment, a text-fragment, and an image-fragment.
  2. The up-fragment contains two seekbar.
  3. Slide the first seekbar will display the text-fragment at the bottom and zoom in or out the text in it.
  4. Slide the second seekbar will display the image-fragment at the bottom and rotate the image while sliding.

3. Fragments Communication Example Source Files.

  1. Below is the example project files list.
    C:\WORKSPACE\WORK\DEV2QA.COM-EXAMPLE-CODE\ANDROIDEXAMPLEPROJECT\ANDROIDFRAGMENT
    │   .gitignore
    │   build.gradle
    │   gradle.properties
    │   gradlew
    │   gradlew.bat
    │   settings.gradle
    │
    ├───.idea
    │       gradle.xml
    │       misc.xml
    │       modules.xml
    │       runConfigurations.xml
    │
    ├───app
    │   │   .gitignore
    │   │   build.gradle
    │   │   proguard-rules.pro
    │   │
    │   └───src
    │       ├───androidTest
    │       │   └───java
    │       │       └───com
    │       │           └───dev2qa
    │       │               └───androidfragment
    │       │                       ExampleInstrumentedTest.java
    │       │
    │       ├───main
    │       │   │   AndroidManifest.xml
    │       │   │
    │       │   ├───java
    │       │   │   └───com
    │       │   │       └───dev2qa
    │       │   │           └───androidfragment
    │       │   │                   ButtonActivity.java
    │       │   │                   ImageFragment.java
    │       │   │                   MainActivity.java
    │       │   │                   TextFragment.java
    │       │   │                   UpFragment.java
    │       │   │
    │       │   └───res
    │       │       ├───drawable
    │       │       │       green_button.jpg
    │       │       │       ic_launcher_background.xml
    │       │       │
    │       │       ├───drawable-v24
    │       │       │       ic_launcher_foreground.xml
    │       │       │
    │       │       ├───layout
    │       │       │       activity_button.xml
    │       │       │       activity_main.xml
    │       │       │       fragment_image.xml
    │       │       │       fragment_text.xml
    │       │       │       up_fragment.xml
    │       │       │
    │       │       ├───mipmap-anydpi-v26
    │       │       │       ic_launcher.xml
    │       │       │       ic_launcher_round.xml
    │       │       │
    │       │       ├───mipmap-hdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       ├───mipmap-mdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       ├───mipmap-xhdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       ├───mipmap-xxhdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       ├───mipmap-xxxhdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       └───values
    │       │               colors.xml
    │       │               strings.xml
    │       │               styles.xml
    │       │
    │       └───test
    │           └───java
    │               └───com
    │                   └───dev2qa
    │                       └───androidfragment
    │                               ExampleUnitTest.java
    │
    └───gradle
        └───wrapper
                gradle-wrapper.jar
                gradle-wrapper.properties
  2. There are four java files and four layout XML files in this example.
  3. MainActivity.java: This is the main activity java file, it must implement UpFragment.OnFragmentInteractionListener interface and override the interface methods.
  4. UpFragment.java: This is the java file that implements the top fragment. It contains two seekbar and the definition of the OnFragmentInteractionListener interface. When the onAttach method is invoked, the activity is assigned to the mListener instance variable.
  5. TextFragment.java: This fragment only contains a TextView object. The text will be zoom in or out when the text seekbar slides.
  6. ImageFragment.java: Only contains an ImageView object. The image will be rotated while the user slides the image seekbar.
  7. activity_main.xml : This is the main activity layout xml file.
  8. up_fragment.xml : This layout xml file is used by UpFragment.java.
  9. fragment_text.xml : Layout xml file used by TextFragment.java.
  10. fragment_image.xml : Layout xml file used by ImageFragment.java.

3.1  Main Activity Java File.

  1. MainActivity.java
    package com.dev2qa.androidfragment;
    
    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.os.Bundle;
    
    public class MainActivity extends AppCompatActivity implements UpFragment.OnFragmentInteractionListener{
    
        // This is the down fragment place holder id.
        private final static int DOWN_FRAGMENT_ID = R.id.down_fragment;
    
        // This is the text fragment object.
        private TextFragment textFragment = null;
    
        // This is the image fragment object.
        private ImageFragment imageFragment = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            setTitle("dev2qa.com - Android Fragment Communication Example.");
    
            initControls();
        }
    
    
        /* Override method in UpFragment.OnFragmentInteractionListener interface. */
        @Override
        public void onTextSeekBarChange(float seekbarValue) {
    
            // Replace the down fragment with textFragment.
            replaceFragment(textFragment, DOWN_FRAGMENT_ID);
    
            // Invoke text fragment method to zoom in / out text size.
            textFragment.changeTextSize(seekbarValue);
        }
    
        @Override
        public void onImageSeekBarChange(float seekbarValue) {
    
            // Replace the down fragment with imageFragment.
            replaceFragment(imageFragment, DOWN_FRAGMENT_ID);
    
            // Invoke image fragment method to rotate the image.
            imageFragment.rotateImage(seekbarValue);
    
        }
    
    
        private void initControls(){
            if(textFragment == null)
            {
                textFragment = new TextFragment();
            }
    
            if(imageFragment == null)
            {
                imageFragment = new ImageFragment();
            }
    
            // Display text fragment at down_fragment.
            replaceFragment(imageFragment, DOWN_FRAGMENT_ID);
        }
    
        // Use destination fragment to replace the fragment displayed in fragment_layout_holder_id.
        public void replaceFragment(Fragment destFragment, int fragment_layout_holder_id)
        {
            // Get FragmentManager object.
            FragmentManager fragmentManager = this.getSupportFragmentManager();
    
            // Begin transaction.
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    
            // Replace the layout holder with the required Fragment object.
            fragmentTransaction.replace(fragment_layout_holder_id, destFragment);
    
            // Commit transaction.
            fragmentTransaction.commit();
        }
    }

3.2 Main Activity Layout Xml File.

  1. activity_main.xml
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <fragment
            android:id="@+id/up_fragment"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:name="com.dev2qa.androidfragment.UpFragment"
            tools:layout="@layout/up_fragment" />
    
        <FrameLayout
            android:id="@+id/down_fragment"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="5"/>
    </LinearLayout>

3.3 Up Fragment Java File.

  1. UpFragment.java
    package com.dev2qa.androidfragment;
    
    import android.content.Context;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.SeekBar;
    
    
    public class UpFragment extends Fragment implements SeekBar.OnSeekBarChangeListener{
    
        // This variable is used to refer to the activity that uses this fragment.
        private OnFragmentInteractionListener mListener;
    
        // The text seekbar.
        private SeekBar textSeekBar = null;
    
        // The image seekbar.
        private SeekBar imageSeekBar = null;
    
        public UpFragment() {
    
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the fragment layout.
            View fragmentView = inflater.inflate(R.layout.up_fragment, container, false);
    
            if(textSeekBar == null)
            {
                textSeekBar = (SeekBar)fragmentView.findViewById(R.id.text_seek_bar);
                textSeekBar.setOnSeekBarChangeListener(this);
            }
    
            if(imageSeekBar == null)
            {
                imageSeekBar = (SeekBar)fragmentView.findViewById(R.id.image_seek_bar);
                imageSeekBar.setOnSeekBarChangeListener(this);
            }
    
            return fragmentView;
        }
    
        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            /* Assign the activity to the variable. Because activity implements OnFragmentInteractionListener
               so the activity is an instance of OnFragmentInteractionListener. */
            if (context instanceof OnFragmentInteractionListener) {
                mListener = (OnFragmentInteractionListener) context;
            } else {
                throw new RuntimeException(context.toString()
                        + " must implement OnFragmentInteractionListener");
            }
        }
    
        @Override
        public void onDetach() {
            super.onDetach();
            mListener = null;
        }
    
        /* This method is invoked when the seekbar slide. Because UpFragment.java implement SeekBar.OnSeekBarChangeListener interface. */
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
            int seekBarId = seekBar.getId();
    
            if(seekBarId == R.id.text_seek_bar)
            {
                // If slide the text seekbar then invoke activity's onTextSeekBar method.
                mListener.onTextSeekBarChange(progress);
            }else if(seekBarId == R.id.image_seek_bar)
            {
                // If slide the image seekbar then invoke activity's onImageSeekBar method.
                mListener.onImageSeekBarChange(progress);
            }
        }
    
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
    
        }
    
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
    
        }
    
        /**
         * The activity must implement the below interface.
         * When seekbar slides, the mListener will invoke the below methods that are implemented in the activity.
         * Activity will display related fragment in the override methods accordingly.
         */
        public interface OnFragmentInteractionListener {
    
            void onTextSeekBarChange(float seekbarValue);
    
            void onImageSeekBarChange(float seekbarValue);
        }
    }

3.4 Up Fragment Layout Xml File.

  1. up_fragment.xml
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.dev2qa.androidfragment.UpFragment"
        android:orientation="vertical">
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Slide the seekbar to change text size :"/>
    
        <SeekBar
            android:id="@+id/text_seek_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:tooltipText="Change below text size"/>
    
        <TextView
            android:layout_marginTop="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Slide the seekbar to rotate image :"/>
    
        <SeekBar
            android:id="@+id/image_seek_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:tooltipText="Rotate below image"/>
    
    
    </LinearLayout>

3.5 Text Fragment Java File.

  1. TextFragment.java
    package com.dev2qa.androidfragment;
    
    import android.content.Context;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.annotation.NonNull;
    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;
    
    
    public class TextFragment extends Fragment {
    
        private TextView textView = null;
    
        /* Used to change textview text size. */
        public void changeTextSize(float textSize)
        {
            if(textView!=null)
            {
                textView.setTextSize(textSize);
            }
        }
    
    
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            // Inflate TextFragment layout.
            View fragmentView = inflater.inflate(R.layout.fragment_text, container, false);
    
            // Get the textview object.
            textView = fragmentView.findViewById(R.id.text_view);
    
            return fragmentView;
        }
    }

3.6 Text Fragment Layout Xml File.

  1. fragment_text.xml
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.dev2qa.androidfragment.TextFragment">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_gravity="center">
    
            <TextView
                android:id="@+id/text_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Hello Fragment."
                android:textSize="20dp"
                android:gravity="center"/>
    
        </LinearLayout>
    
    </FrameLayout>

3.7 Image Fragment Java File.

  1. ImageFragment.java
    package com.dev2qa.androidfragment;
    
    import android.graphics.Bitmap;
    import android.graphics.Canvas;
    import android.graphics.Paint;
    import android.graphics.drawable.BitmapDrawable;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageView;
    import android.graphics.Matrix;
    import android.graphics.Bitmap.Config;
    
    
    public class ImageFragment extends Fragment {
    
        private ImageView imageView = null;
    
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View ret = inflater.inflate(R.layout.fragment_image, container, false);
    
            // Get the imageview object.
            imageView = (ImageView)ret.findViewById(R.id.image_view);
    
            return ret;
        }
    
        /* Used to rotate the image. */
        public void rotateImage(float rotateAngel)
        {
            BitmapDrawable originalBitmapDrawable = (BitmapDrawable) imageView.getDrawable();
    
            Bitmap originalBitmap = originalBitmapDrawable.getBitmap();
    
            int originalImageWith = originalBitmap.getWidth();
    
            int originalImageHeight = originalBitmap.getHeight();
    
            Config originalImageConfig = originalBitmap.getConfig();
    
            // Create a bitmap that has the same width and height value as the original bitmap.
            Bitmap rotateBitmap = Bitmap.createBitmap(originalImageWith, originalImageHeight, originalImageConfig);
    
            Canvas rotateCanvas = new Canvas(rotateBitmap);
    
            Matrix rotateMatrix = new Matrix();
    
            // Rotate around the center point of the original image.
            rotateMatrix.setRotate(rotateAngel, originalBitmap.getWidth()/2, originalBitmap.getHeight()/2);
    
            Paint paint = new Paint();
            rotateCanvas.drawBitmap(originalBitmap, rotateMatrix, paint);
            imageView.setImageBitmap(rotateBitmap);
        }
    }

3.8 Image Fragment Layout Xml File.

  1. fragment_image.xml
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.dev2qa.androidfragment.ImageFragment">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:gravity="center">
    
            <ImageView
                android:id="@+id/image_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/green_button" />
    
        </LinearLayout>
    
    </FrameLayout>

Reference

  1. Android Add Fragment To Activity Dynamically Example
  2. Android ImageView Matrix Rotate, Scale, Skew, Translate Example
  3. Android Fragment

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.