Android Fragment represents a behavior or a portion of the user interface in an Activity (or in FragmentActivity). You can use multiple fragments in a single activity to build a multi-pane UI and can reuse a fragment in multiple activities.
To Use fragments in android you have to build reusable and self-contained modular components. In the process, some time Activity has multiple Fragments and one fragment can depend on other actions or data. So here we are solving and sharing basic Communication between two fragments example.
Consider my 2 fragments Sender and Receiver, and Suppose you need to pass data from Sender to Receiver.
Then create an interface in the Sender, and pass the data to the Main Activity. Then From the main activity to pass data fragment Receiver.
Let’s start building basic: How to pass data between fragments
Step 1. Create an android project in the android studio (Android First Program in Android Studio)
Step 2. Create 2 fragments in activity_main.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.basiccommunicationbetweenfragments.MainActivity"> <fragment android:id="@+id/frg_Receiver" android:name="in.eyehunt.basiccommunicationbetweenfragments.ReceiverFragment" android:layout_width="match_parent" android:layout_height="0dp" android:layout_marginBottom="8dp" android:layout_marginEnd="8dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" app:layout_constraintBottom_toTopOf="@+id/frg_Sender" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> </fragment> <fragment android:id="@+id/frg_Sender" android:name="in.eyehunt.basiccommunicationbetweenfragments.SenderFragment" 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" app:layout_constraintTop_toBottomOf="@+id/frg_Receiver"> </fragment> </android.support.constraint.ConstraintLayout>
Step 3. Create a layout file for sender fragment with a button to send a message
Before copy paste code add color code in res/values/colors.xml otherwise an error will spoil your mood.
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#009688</color> <color name="colorPrimaryDark">#00796b</color> <color name="colorAccent">#ff9e80</color> <color name="colorSen">#795b00</color> <color name="colorRec">#a080ff</color> <color name="White">#ffffff</color> </resources>
Then sender 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" android:background="@color/colorSen" tools:context="in.eyehunt.basiccommunicationbetweenfragments.SenderFragment"> <Button android:id="@+id/btn_sender" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_gravity="center" android:gravity="center" android:text="Send Hello" /> </RelativeLayout>
Step 4. Create Sender fragments from the interface
Interface for communication public interface SenderFragmentListener {... }
, with a method void messageFromSenderFragment(String msg);
package in.eyehunt.basiccommunicationbetweenfragments; import android.content.Context; 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.Button; public class SenderFragment extends Fragment { SenderFragmentListener mCommunication; public SenderFragment() {}// Required empty public constructor @Override public void onAttach(Context context) { super.onAttach(context); mCommunication = (SenderFragmentListener) context; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_sender, container, false); Button button = (Button) view.findViewById(R.id.btn_sender); // on click button button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCommunication.messageFromSenderFragment("Hello Fragment i am Sender..."); } }); return view; } //Interface for communication public interface SenderFragmentListener { void messageFromSenderFragment(String msg); } @Override public void onDetach() { super.onDetach(); mCommunication = null; } }
Step 6. Create a layout file for receiver fragment with TextView to show
<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" android:background="@color/colorRec" tools:context="in.eyehunt.basiccommunicationbetweenfragments.ReceiverFragment"> <TextView android:id="@+id/tv_receiver" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:gravity="center" android:text="Receiver" android:textColor="@color/White" android:textSize="18sp"/> </RelativeLayout>
Step 7. Create a fragment for a receiver
with receiving message method public void youGotMsg(String msg) {...}
, this method will be called by Activity. In the method, you can do the operation. here we are showing a message in TextView tv_msg.setText(msg);
package in.eyehunt.basiccommunicationbetweenfragments; 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.TextView; public class ReceiverFragment extends Fragment { TextView tv_msg; public ReceiverFragment(){} // Required empty public constructor @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_receiver, container, false); tv_msg = (TextView) view.findViewById(R.id.tv_receiver); return view; } //Receive message public void youGotMsg(String msg) { tv_msg.setText(msg); } }
Step 8. Final step add following code in MainActivity.java
Implements interface implements SenderFragment.SenderFragmentListener
in activity and override Method @Override public void messageFromSenderFragment(String msg) {}
, then send a message to another fragment.
package in.eyehunt.basiccommunicationbetweenfragments; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity implements SenderFragment.SenderFragmentListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public void messageFromSenderFragment(String msg) { FragmentManager manager = getSupportFragmentManager(); ReceiverFragment mReceiverFragment = (ReceiverFragment)manager.findFragmentById(R.id.frg_Receiver); mReceiverFragment.youGotMsg(msg); } }
Step 9. Now Run the application, in an emulator or On your Android device
Output Screenshot: Before
After click button “SEND HELLO”
Download Link and Source code in Github
https://github.com/EyeHunts/BasicCommunicationbetweenfragments/
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
Bonus: For share data between fragment using ViewModel check this tutorial: Share data between fragments used ViewModel example