Interaction Between Two Fragments

Overview
 
If you are new in the development of the Android application, the below articles are useful to start with.

Introduction

 
In this article, I will explain how to make the interaction between the two fragments.
 
Most of the time, an activity can contain one or more fragments working together to present a logical UI to the user. It is very important for fragments to communicate with one another and exchange data. For example, there is one fragment that might contain a list of items ( product name list). When the user taps on an item in that fragment, details about the selected item may be displayed in another fragment.
 
Coding
 
Fragment1.xml file has only TextView control.
  1. <LinearLayout    
  2.     xmlns:android="http://schemas.android.com/apk/res/android"    
  3.     xmlns:tools="http://schemas.android.com/tools"    
  4. android:layout_width="fill_parent"    
  5. android:layout_height="fill_parent"    
  6. android:orientation="vertical"    
  7. android:background="#00FF00"    
  8. tools:context="com.example.administrator.myfragmentapp.Fragment1Activity">    
  9.     <TextView android:text="@string/Fragment1"    
  10. android:layout_width="fill_parent"    
  11. android:layout_height="wrap_content"    
  12. android:textColor="#000FFF"    
  13. android:layout_marginTop="20dp"    
  14. android:textSize="30dp"    
  15. android:id="@+id/labelFragment1"    
  16. />    
  17. </LinearLayout>    
Fragment2.xml file has a TextView and Button control.
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  2.      xmlns:tools="http://schemas.android.com/tools"    
  3.      android:layout_width="fill_parent"    
  4.      android:layout_height="fill_parent"    
  5.      android:orientation="vertical"    
  6.      tools:context="com.example.administrator.myfragmentapp.Fragment2Activity">    
  7.      
  8.      <TextView android:text="This is 2nd Fragment!"    
  9.          android:layout_width="fill_parent"    
  10.          android:layout_height="wrap_content"    
  11.          android:layout_marginTop="20dp"    
  12.          android:textSize="30dp"/>    
  13.      <Button    
  14.          android:id="@+id/buttonGet"    
  15.          android:layout_width="wrap_content"    
  16.          android:layout_height="wrap_content"    
  17.          android:text="Get text in Ist fragment"    
  18.          android:textColor="#111000"    
  19.          android:onClick="onClick" />    
  20.  </LinearLayout>   
I have implemented one method called onStart() in Fragment2Activity.java class.
  1. package com.example.administrator.myfragmentapp;    
  2.      
  3.  import android.app.Fragment;    
  4.  import android.support.v7.app.ActionBarActivity;    
  5.  import android.os.Bundle;    
  6.  import android.view.LayoutInflater;    
  7.  import android.view.Menu;    
  8.  import android.view.MenuItem;    
  9.  import android.view.View;    
  10.  import android.view.ViewGroup;    
  11.  import android.widget.Button;    
  12.  import android.widget.TextView;    
  13.  import android.widget.Toast;    
  14.      
  15.  public class Fragment2Activity extends Fragment {    
  16.      
  17.      @Override    
  18.      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)    
  19.      {    
  20.          return inflater.inflate(R.layout.activity_fragment2,container,false);    
  21.      }    
  22.      @Override    
  23.      public void onStart(){    
  24.          super.onStart();    
  25.          Button buttonGet = (Button)getActivity().findViewById(R.id.buttonGet);    
  26.          buttonGet.setOnClickListener(new View.OnClickListener() {    
  27.              @Override    
  28.              public void onClick(View view) {    
  29.                  TextView label=(TextView)getActivity().findViewById(R.id.labelFragment1);    
  30.                  Toast.makeText(getActivity(),label.getText(),Toast.LENGTH_SHORT).show();    
  31.              }    
  32.          });    
  33.      }    
  34.  }   
In MainActivity.java class, I  added code to put fragmentTransaction as per the calculation of width and height at run time, in the back stack.
  1. package com.example.administrator.myfragmentapp;    
  2.      
  3.  import android.app.FragmentManager;    
  4.  import android.app.FragmentTransaction;    
  5.  import android.support.v7.app.ActionBarActivity;    
  6.  import android.os.Bundle;    
  7.  import android.view.Display;    
  8.  import android.view.Menu;    
  9.  import android.view.MenuItem;    
  10.  import android.view.WindowManager;    
  11.      
  12.  public class MainActivity extends ActionBarActivity {    
  13.      
  14.      @Override    
  15.      protected void onCreate(Bundle savedInstanceState) {    
  16.          super.onCreate(savedInstanceState);    
  17.         setContentView(R.layout.activity_main);    
  18.      }    
  19.      
  20.      @Override    
  21.      public boolean onCreateOptionsMenu(Menu menu) {    
  22.          // Inflate the menu; this adds items to the action bar if it is present.    
  23.          getMenuInflater().inflate(R.menu.menu_main, menu);    
  24.          return true;    
  25.      }    
  26.      
  27.      @Override    
  28.      public boolean onOptionsItemSelected(MenuItem item) {    
  29.          // Handle action bar item clicks here. The action bar will    
  30.          // automatically handle clicks on the Home/Up button, so long    
  31.          // as you specify a parent activity in AndroidManifest.xml.    
  32.          int id = item.getItemId();    
  33.      
  34.          //noinspection SimplifiableIfStatement    
  35.          if (id == R.id.action_settings) {    
  36.              return true;    
  37.          }    
  38.      
  39.          return super.onOptionsItemSelected(item);    
  40.      }    
  41.  }   
Result- Run the application by pressing Shift + F10 on the Android emulator.
 
 
In the second fragment on the right, click the button. You will see the Toast class displaying the text "This is Item# 1 of Ist Fragment!"
 
 
Explanation
 
The two fragments are embedded within activities. We can obtain the activity, in which a fragment is currently embedded, by first using the getActivity() method and then using the findViewById() method to locate the Views contained within the fragment.
  1. buttonGet.setOnClickListener(new View.OnClickListener() {    
  2.      @Override    
  3.      public void onClick(View view) {    
  4.          TextView label=(TextView)getActivity().findViewById(R.id.labelFragment1);    
  5.          Toast.makeText(getActivity(),label.getText(),Toast.LENGTH_SHORT).show();    
  6.      }    
  7.  });  
The getActivity() method returns the activity with which the current fragment is currently associated.
 

Conclusion

 
In this article, I have explained about the interaction between two fragments. In the next article, I will explain about calling built-in applications using Intents. If you have any questions or comments, post me a message in the C# Corner comments section.


Similar Articles