Android Fragment Communication With Activity Example

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

1. Communication Between Android Fragments And Activity.

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 activity code.

If you want the fragment to pass data to related activity, you can follow below steps.

  1. Define an interface which contains methods that fragment want the activity to override.
  2. Make the activity implement above interface and override the methods declared in it.
  3. 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.

android fragment communication with activity example

  1. There are three fragments in this example. A 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 bottom and zoom in or out the text in it.
  4. Slide the second seekbar will display the image-fragment at bottom and rotate the image while sliding.

3. Fragments Communication Example Source Files.

android fragments communication example source files

There are four java files and four layout xml files in this example.

  1. MainActivity.java : This is the main activity java file, it must implement UpFragment.OnFragmentInteractionListener interface and override the interface methods.
  2. UpFragment.java : This is the java file which implement the top fragment. It contains two seekbar and definition of OnFragmentInteractionListener interface. When the onAttach method invoked, the activity is assigned to the mListener instance variable.
  3. TextFragment.java : This fragment only contains a TextView object. The text will be zoom in or out when text seekbar slide.
  4. ImageFragment.java : Only contains an ImageView object. The image will be rotated while user slide the image seekbar.
  5. activity_main.xml : This is the main activity layout xml file.
  6. up_fragment.xml : This layout xml file is used by UpFragment.java.
  7. fragment_text.xml : Layout xml file used by TextFragment.java.
  8. fragment_image.xml : Layout xml file used by ImageFragment.java.

3.1  Main Activity Java File.

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.

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.

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 use 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 mtehod.
            mListener.onImageSeekBarChange(progress);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    /**
     * The activity must implement below interface.
     * When seekbar slide, the mListener will invoke below methods that is 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.

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.

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.

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.

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 which has same width and height value of 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.

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
(Visited 1,490 times, 11 visits today)
READ :   Android Analog, Digital And Text Clock Example

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.