Android developers must know what is activity, what is fragments and why and how to use them. But many of them feel it difficult when it comes to the communication between an activity and a fragment.
Today in this tutorial I will be showing you how an activity and a fragment communicates. I got so many comments and feedback that they know the theory about activity and fragment and know how to use the individually, but they don’t know how these two components of android can communicate together. Below are the links of the blogs I have posted earlier on fragments and activity.
And many more….
Lets first see a short algorithm what we will be doing
Now we will create a working example for the same in which we will link two different fragments the sender and the receiver into our main activity. The fragments will be used to Send and Receive messages, i.e. One fragment will send messages to another fragment which will display the messages sent from first fragment. Let’s follow the steps below:
Step1: Create a new android project in your android IDE.
Step2: Create and write following into receiverfragment.xml:
<?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 = "Type to send message" > <requestFocus /> </TextView> </LinearLayout>
Step3: Create and write following into senderfragment.xml:
<?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>
Step4: Create and write following into SenderFragment.java:
package com.example.activityfragmentscommunication; 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.senderfragment, 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) { 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); } }
Step5: Create and write following into ReceiverFragment.java:
package com.example.activityfragmentscommunication; 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.receiverfragment, container); } void setReceivedText(String msg) { TextView textView = (TextView) this.getView().findViewById(R.id.textView1); textView.setText(msg); } }
Step6: Write following into main layout file:
<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.example.activityfragmentscommunication.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.example.activityfragmentscommunication.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>
Step7: Write following into main activity file:
package com.example.activityfragmentscommunication; 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.menu_main, menu); return true; } @Override public void setCommunication(String msg) { ReceiverFragment recFragment = (ReceiverFragment)getFragmentManager().findFragmentById(R.id.fragment1); if(null != recFragment && recFragment.isInLayout()) { recFragment.setReceivedText(msg); } } }
Android Components – The Activity
How To Use Custom Fonts In Android
How To Use Build-in Android Themes In Your Application
How To Get Installed Activity List
How To Get FileExplorer History In Android Development
Start Activity Using ACTION_VIEW Intent For Selected MIME Type In Android
Learn How To Create ListView From SQLite Database In Android Development
Clipboard Activity In Android Development