Communication Between Fragments In Android

Introduction

 
Here I will explain the communication between fragments in Android. The following is a brief description of the task that I am going to show you.
 
I have an Activity with two fragments, lets name that fragments to FragmentA and Fragment B. FragmentA contains a Button and FragmentB contains a textview
 
Each time the user clicks on the Button of FragmentA then the textview in the FragmentB will update its text like "this button is clicked <counter> times".
 
This is the task I am going to show you.
 
For this first, create FragmentA and its Layout,
  1. <?xml version="1.0" encoding="utf-8"?>      
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:background="@android:color/darker_gray" android:layout_height="match_parent">      
  3.     <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Me" android:layout_margin="20dp" android:id="@+id/button" android:layout_gravity="center_horizontal" />      
  4. </LinearLayout>     
    The FragmentA contains a Button and in the java code please load the XML file in onCreateView();
     
    Now create FragmentB and its Layout,
    1. <?xml version="1.0" encoding="utf-8"?>      
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:background="@android:color/white" android:layout_height="match_parent">      
    3.     <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="20dp" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Large Text" android:id="@+id/textView" android:layout_gravity="center_horizontal" />      
    4. </LinearLayout>     
      FragmentB contains a Textview only. load this layout to FragmetB class on the onCreateView() 
       
      Now create the main part of the task that is communicator  Interface.
      1. public interface Communicator     
      2. {    
      3.     public void clicked(String text);    
      4. }   
      Now create the MainActivity that implement Communicator Interface,
      1. public class MainActivity extends Activity implements Communicator    
      2. {    
      3.     @Override    
      4.     protected void onCreate(Bundle savedInstanceState)     
      5.     {    
      6.         super.onCreate(savedInstanceState);    
      7.         setContentView(R.layout.activity_main);    
      8.     }    
      9.     @Override    
      10.     public void clicked(String text)    
      11.     {    
      12.         FragmentB b = (FragmentB) getFragmentManager().findFragmentById(R.id.fragment2);    
      13.         b.chageText(text);    
      14.     }    
      15. }   
        The clicked method will call another method named changeText(String) in Fragment B. Now we need to notify the communicator Interface when Button in FragmentA is clicked and create a method chageText(String) in FragmentB.
         
        Now create Button Click Event in FragmentA. This is how the FragmentA will look like,
        1. public class FragmentA extends Fragment    
        2. {    
        3.     private int counter = 0;    
        4.     private Communicator comm = null;    
        5.     @Nullable    
        6.     @Override    
        7.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)    
        8.     {    
        9.         return inflater.inflate(R.layout.fragment_a, container, false);    
        10.     }    
        11.     @Override    
        12.     public void onActivityCreated(Bundle savedInstanceState)     
        13.     {    
        14.         super.onActivityCreated(savedInstanceState);    
        15.         Button button = (Button) getActivity().findViewById(R.id.button);    
        16.         comm = (Communicator) getActivity();    
        17.         button.setOnClickListener(new View.OnClickListener()    
        18.         {    
        19.             @Override    
        20.             public void onClick(View view)    
        21.             {    
        22.                 counter++;    
        23.                 comm.clicked("This button is clicked " + counter + " times");    
        24.             }    
        25.         });    
        26.     }    
        27. }   
          On the onActivityCreated() we are initializing the communicator with the FragmentA, and in the button click we are firing the interface method()
           
          Now Create the FragmentB,
          1. public class FragmentB extends Fragment    
          2. {    
          3.     private TextView textView = null;    
          4.     @Nullable    
          5.     @Override    
          6.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)    
          7.     {    
          8.         return inflater.inflate(R.layout.fragment_b, container, false);    
          9.     }    
          10.     @Override    
          11.     public void onActivityCreated(Bundle savedInstanceState)    
          12.     {    
          13.         super.onActivityCreated(savedInstanceState);    
          14.         textView = (TextView) getActivity().findViewById(R.id.textView);    
          15.     }    
          16.     public void chageText(String data)    
          17.     {    
          18.         textView.setText(data);    
          19.     }    
          20. }   
            There will be a method named chageText to change the content of textView in FragmentB. This is the way in which the fragments communicate in Android.
             
            The output will look as follows,
             
             
             
            Read more articles on Android