Communication Between Activity and Fragment Example

Communication Between Activity and Fragment Example

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

After received many requests from online users of my Android blog, I have posted the complete tutorial about the communication between activity and fragment Example. Here you can learn how a simple fragment can communicates with an Activity in Android. We will use simple  getFragmentManager() API  and Fragment Class in Android to complete this task .

We need below steps to understand the fundamental logic behind Activity and Fragment communication in Android.

  1. Create a new Android Project
  2. Create an Activity.
  3. Create a Fragment
  4. Link the Fragment with the Activity
  5. Create a simple Interface (Which will be the medium of communication)
  6. Send and Receive Messages.

Now lets go to the programming parts. Lets first create a new android project using eclipse. You can follow the same process just like the HelloWorld application.

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

  • Create a New Android Project in Eclipse

 

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.fragmentcommunication”, You can mention your own package but if you want to sync with example then please mention the same package name.
  • Create an Activity.
  1. Then keep the default Activity Name as MainActivity shown in the below snapshot. Then click next/finish button to complete the new Android Project creation.

 

 

  •  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.

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.

 

 

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

 

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 MainActivity.

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.

<?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” >

<EditText
android:id=”@+id/editText1″
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:ems=”10″ >

<requestFocus />
</EditText>

<Button
android:id=”@+id/button1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Send Message”/>

</LinearLayout>

Now we will create two Java classes (SenderFragment and ReceiverFragmentcorresponding 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.

  • ReceiverFragment.java

Copy and paste below code snippet into your  ReceiverFragment.java file in your project. Make sure to edit the package name if you are using different package name in your code. The ReceiverFragment 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;

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

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 MainActivity.

To do this task, we will link both fragment xml files into our MainActivity’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/fragment1″
android:name=”com.techblogon.fragmentcommunication.ReceiverFragment”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentLeft=”true”
android:layout_alignParentTop=”true”
android:layout_marginLeft=”124dp”
android:layout_marginTop=”76dp” />

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

<RelativeLayout 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=”.MainActivity” >

<fragment
android:id=”@+id/fragment1″
android:name=”com.techblogon.fragmentcommunication.ReceiverFragment”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentLeft=”true”
android:layout_alignParentTop=”true”
android:layout_marginLeft=”124dp”
android:layout_marginTop=”76dp” />

<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” />

</RelativeLayout>

  •  Create a simple Interface

Now we will create a simple interface inside the SenderFragment Java class (which we created just before), so that we can Override one predefined method in our MainActivity 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 SenderFragment class for click functionality. So now after created the interface inside the SenderFragment class your  SenderFragment class will be look like below.

Better you just copy paste the below code into your previous SenderFragment  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 ReceiverFragment 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 ReceiverFragment  class.

After added the above  code into your ReceiverFragment  class. Your code will be look like below. Also you can just copy and paste below code into your ReceiverFragment  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 MainActivity 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 setCommunication(). We will send the message to Receiver Fragment class inside the function setCommunication(). So After implemented the interface in the MainActivity class and @Override it’s function setCommunication(), Your MainActivity Java class will looks like below.

Also you can directly copy and paste below code into your MainActivity.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 && recFragment.isInLayout())
{
recFragment.setReceivedText(msg);
}

}
}

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

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

Leave a Reply

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