Skip to content

Activity and Fragments communication | Example code

Activity and fragment communication are important when you want to update data or action. You can do communication between Activity and Fragments using the interface. It’s required much time to pass data between activity and fragments or Fragments to fragments.

Activity and Fragments communication example

Communication Fragments to Activity :

The easiest way to communicate between your activity and fragments is using interfaces. The idea is basically to define an interface inside a given Fragments and let the activity implement that interface.

// Interface - fragment to activity
    public interface SendMessages {
        void iAmMSG(String msg);
    }

Once it has implemented that interface, you could do anything you want in the method it overrides.

public class MainActivity extends AppCompatActivity implements MyFragment.SendMessages {

    ........
    // receive data form fragments
    @Override
    public void iAmMSG(String msg) {
        tv_activity.setText(msg);
    }
}

The other important part of the interface is that you have to call the abstract method from your fragment and remember to cast it to your activity. It should catch a ClassCastException, if not done correctly.

 

Communication Activity to Fragments :

Its very easy to do, create a method in Fragments and in Activity create an instance of fragments and pass data in methods. it’s a flexible way when the fragment is already launched and Fragments want data from an Activity.

Method in fragment 

//Receive message - activity to fragment
    public void receiveMsg(String msg) {
        tv_frag.setText(msg);
    }

Create an instance in activity and pass data to fragment 

FragmentManager manager = getSupportFragmentManager();
MyFragment myFragment = (MyFragment) manager.findFragmentById(R.id.myfrag);
myFragment.receiveMsg("Hi Fragment how are you ?");

Maybe chance you have to another way or requirement, then you have to choose as per needs.

 

Situation: How to access a variable in activity from a fragment?

It’s a common situation when developer facing this kind of a problem during application developer. In this example, we are doing the same thing or you will get an idea of how to do it.

 

Let’s build Android app for Activity and Fragments communication

Step 1. Create new project “Build Your First Android App in Kotlin
Step 2. Add color in app>res>values>colors.xml
<resources>
    <color name="colorWhite">#ffffff</color>
</resources>
Step 3. Create new fragment with the resource file

Resource file “fragment_my.xml” with 2 TextView and a Button widget

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent"
    android:orientation="vertical"
    android:padding="8dp"
    tools:context="in.eyehunt.activityfragmentcommunication.MyFragment">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Fragment"
        android:textColor="@color/colorWhite"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:textSize="18sp"/>
    
    <TextView
        android:id="@+id/tv_fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:text=""
        android:textColor="@color/colorWhite"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <Button
        android:id="@+id/btn_send"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:text="Button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tv_fragment" />

</android.support.constraint.ConstraintLayout>

Now in Fragment class, “MyFragment.java” add the following code

package in.eyehunt.activityfragmentcommunication;

import android.content.Context;
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.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MyFragment extends Fragment {

    private SendMessages sendMessages;
    TextView tv_frag;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        sendMessages = (SendMessages) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my, container, false);
        tv_frag = (TextView) view.findViewById(R.id.tv_fragment);

        // on click button pass data
        Button send = (Button) view.findViewById(R.id.btn_send);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessages.iAmMSG("Hello I am fragment ");
            }
        });
        return view;
    }

    // Interface - fragment to activity
    public interface SendMessages {
        void iAmMSG(String msg);
    }

    //Receive message - activity to fragment
    public void receiveMsg(String msg) {
        tv_frag.setText(msg);
    }
}
Step 4. Add fowling code in main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="in.eyehunt.activityfragmentcommunication.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Activity"
        android:textSize="18sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tv_activity"
        android:layout_width="match_parent"
        android:layout_height="44dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="12dp"
        android:text=""
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <Button
        android:id="@+id/btn_send_act"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="16dp"
        android:text="Button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tv_activity" />


    <fragment
        android:id="@+id/myfrag"
        android:name="in.eyehunt.activityfragmentcommunication.MyFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent" />

</android.support.constraint.ConstraintLayout>
Step 5. Add fowling code in MainActivity.java
package in.eyehunt.activityfragmentcommunication;

import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements MyFragment.SendMessages {

    TextView tv_activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_activity = (TextView) findViewById(R.id.tv_activity);

        Button btn_send_act = (Button) findViewById(R.id.btn_send_act);
        //send message to fragment
        btn_send_act.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager manager = getSupportFragmentManager();
                MyFragment myFragment = (MyFragment) manager.findFragmentById(R.id.myfrag);
                myFragment.receiveMsg("Hi Fragment how are you ?");
            }
        });
    }

    // receive data form fragments
    @Override
    public void iAmMSG(String msg) {
        tv_activity.setText(msg);
    }
}
Step 6. Run the application, in the emulator or On your android device
Output screenshot Activity and fragments communication example
Activity and fragments communication example

Video

Download source code Activity and fragments communication example :

https://github.com/EyeHunts/ActivityFragmentcommunication

 

Note : This example (Project) is developed in Android Studio 3.0.1 ,tested on Android 7.1.1 ( Android Nougat), compile SDK version API 26: Android 8.0 (Oreo)

MinSdkVersion=”15″

TargetSdkVersion=”26″

Coding in Java

2 thoughts on “Activity and Fragments communication | Example code”

Leave a Reply

Your email address will not be published. Required fields are marked *