Communication Between Activity and Fragment Example

Communication Between Activity and Fragment Example

After received many requests from online users of my Android blog, I even have posted the whole tutorial about the communication between activity and fragment Example. Here you’ll find out how an easy fragment can communicates with an Activity in Android. we’ll use simple get Fragment Manager() API and Fragment Class in Android to finish this task .
We need below steps to know the elemental logic behind Activity and Fragment communication in Android.

  1. Create a replacement Android Project.
  2. Create an Activity.
  3. Create a fraction.
  4. Link the Fragment with the Activity.
  5. Create an easy Interface (Which are going to be the medium of communication).
  6. Send and Receive Messages.

Now lets attend the programming parts. Lets first create a replacement android project using eclipse. you’ll follow the same process a touch just like the HelloWorld application.

To sync with the instance here, it’s better to use the same project name and package name which is mentioned in below snapshot. Anyway you’ll choose your own.

  • Create a New Android Project in Eclipse
Communication Between Activity and Fragment Example

Note: 

  1. Please make sure to select Minimum Required SDK as API11: Android 3.0 (Honeycomb) as shown in the above screenshot else it will give errorBecause fragment was introduced from Honeycomb Android OS. You can also change this  later in the Android Manifest file.
  2. You can see I have mentioned the Package Name as “com.techblogon.fragment communication”, You can mention your own package but if you want to sync with example then please mention the same package name.
  3. Create an Activity.
  4. Then keep the default Activity Name as Main Activity shown in the below snapshot. Then click next/finish button to complete the new Android Project creation.
Communication Between Activity and Fragment Example
  •  Create a Fragment

Now it is time to create 2 new fragments in our application to demonstrate the communication between Fragments and Activity in Android. It is very easy to create fragments in Android. Please follow below steps.

Communication Between Activity and Fragment Example


Once you click on Android XML File then you can see below dialog to enter fragment name. Enter File name as receiver_fragment and press Finish.

Communication Between Activity and Fragment Example

Similarly repeat the same steps as above to create another fragment (called sender_fragment). Follow below snapshot for more details.

Communication Between Activity and Fragment Example

Now we will add one Text View into receiver_fragment.xml file, so that we will display the message which will be send by receiver_fragment via Activity. To add a Test View, Please go to your receiver_fragment.xml file (under res->layout folder in your application). Once you add the Text View then your receiver_fragment.xml file will be look like below. Also You can copy below code into your receiver_fragment.xml file directly.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text = "No Text now" >

        <requestFocus />
    </TextView>

</LinearLayout>

Now in the same way we will add one Edit View and a Button control into our sender_fragment.xml file, so that we can type some message and send it our receiver_fragment via the Main Activity.

After added one Edit Text and one Button then your sender_fragment xml file will be look like below. You can also directly copy and paste below code into your sender_fragment.xml file.

Now we will create two Java classes (Sender Fragment and Receiver Fragmentcorresponding to our fragment files (receiver_fragment.xml and sender_fragment.xml). Here we will attach our fragment xml files to our corresponding fragment java classes. The Java file will contain the logic for the fragment as per our requirement. Also you can directly copy and paste below Java files into your project.

Communication Between Activity and Fragment Example
  • Receiver Fragment.java

Copy and paste below code snippet into your  Receiver Fragment.java file in your project. Make sure to edit the package name if you are using different package name in your code. The Receiver Fragment java class will link to our receiver_fragment xml  file for showing GUI.

package com.techblogon.fragmentcommunication;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class ReceiverFragment extends Fragment
{
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
	{
		return inflater.inflate(R.layout.receiver_fragment, container);
	}

}
  • SenderFragment.java

Similarly now copy and paste below code snippet into your  SenderFragment.java file in your project. Make sure to edit the package name if you are using different package name in your code.

package com.techblogon.fragmentcommunication;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class SenderFragment extends Fragment
{
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
	{
		return inflater.inflate(R.layout.sender_fragment, container);
	}

}
  •  Link the Fragment with the Activity

Now we will link above two fragments (receiver_fragment.xml and sender_fragment.xml) with our Main Activity.

To do this task, we will link both fragment xml files into our Main Activity’s XML file (activity_mail.xml).  It means add 2 fragment controls into your activity_main.xml file. You can copy below code into your activity_main.xml file.

<fragment
    android:id="@+id/fragment2"
    android:name="com.techblogon.fragmentcommunication.SenderFragment"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/fragment1"
    android:layout_marginLeft="96dp"
    android:layout_marginTop="124dp" />

Once you add and link above two fragments code into your activity_main.xml file then the your code will be look like below.

  •  Create a simple Interface

Now we will create a simple interface inside the Sender Fragment Java class (which we created just before), so that we can Override one predefined method in our Main Activity Java class for communication. Confused!. Don’t worry we will explain later in code once we created the interface. Also we will add one button click event inside Sender Fragment class for click functionality. So now after created the interface inside the Sender Fragment class your  Sender Fragment class will be look like below.

Better you just copy paste the below code into your previous Sender Fragment  Java file.

package com.techblogon.fragmentcommunication;


import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class SenderFragment extends Fragment
{
	CommunicationChannel mCommChListner = null;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
	{
		
		View view = (View) inflater.inflate(R.layout.sender_fragment, container);
	    final EditText editText = (EditText)view.findViewById(R.id.editText1);
		Button mButton = (Button) view.findViewById(R.id.button1);
		mButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v) 
			{
				// TODO Auto-generated method stub
				String str = editText.getText().toString();
				sendMessage(str); 
			}
		});
		return view;
	}

	//create an interface which will help us to communicate with fragments by help of Activity 
	interface CommunicationChannel
	{
		public void setCommunication(String msg);
	}
	
	@Override
	public void onAttach(Activity activity) 
	{
		super.onAttach(activity);
		if(activity instanceof CommunicationChannel)
		{
			mCommChListner = (CommunicationChannel)activity;
		}
		else 
		{
			throw new ClassCastException();
		}
		
	}
	public void sendMessage(String msg)
	{
		mCommChListner.setCommunication(msg);
	}
}

Now coming to the Receiver Fragment Java Class. Just add a new function to display the received message (from Sender fragment via Activity and the Interface ) on the fragment screen. Add below code snippet into your Receiver Fragment  class.

void setReceivedText(String msg)
	{
		TextView textView = (TextView) this.getView().findViewById(R.id.textView1);
		textView.setText(msg);
	}

After added the above  code into your Receiver Fragment  class. Your code will be look like below. Also you can just copy and paste below code into your Receiver Fragment  class directly.

package com.techblogon.fragmentcommunication;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class ReceiverFragment extends Fragment
{
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
	{
		return inflater.inflate(R.layout.receiver_fragment, container);
	}
	
	void setReceivedText(String msg)
	{
		TextView textView = (TextView) this.getView().findViewById(R.id.textView1);
		textView.setText(msg);
	}

}
  •  Send and Receive Messages

Now coming to our Main Activity Java class to link the communication. Here we will get the message  from Sender Fragment and send it to Receiver Fragment. To do this activity, we have to implement the previously created interface (CommunicationChannel) and then override it’s function set Communication()We will send the message to Receiver Fragment class inside the function set Communication()So After implemented the interface in the Main Activity class and @Override it’s function set Communication(), Your Main Activity Java class will looks like below.

Also you can directly copy and paste below code into your Main Activity.java file.

package com.techblogon.fragmentcommunication;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity implements SenderFragment.CommunicationChannel
{

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void setCommunication(String msg) 
	{
		// TODO Auto-generated method stub
		ReceiverFragment recFragment = (ReceiverFragment)getFragmentManager().findFragmentById(R.id.fragment1);
		if(null != recFragment  &amp;&amp; recFragment.isInLayout())
		{
			recFragment.setReceivedText(msg);
		}
		
	}
}

You are done now from coding side. Now we will run this application and write some message into Sender Fragment GUI. When we will click on “Send Message” button we can see the message in the Receiver Fragment GUI.

I hope this detailed tutorial about Communication Between Activity and Fragment will help at it’s best.

Download Source Code and Example for Communication Between Activity and Fragment in Android.

allntech.com

Leave a Comment