Fragments in Android

Introduction

 
A fragment is a reusable UI that is used to provide re-usability and for better management of screen space of a user's device. It was introduced in HONEYCOMB i.e. Android 3.0 (API level 11).

If you need to use fragments for API below 11 you will need to import android-support-v4.jar to your project dependencies.

Fragments can be used in two ways:
  1. Direct in XML.
  2. Dynamically adding the Fragment using code. This will need a frame layout to add the fragment.
If we use the 1st method we cannot replace the fragment with other fragments but if we dynamically add a fragment we can always replace and make transition animations on the fragment.

Let's start with the application.

1. Create a new project and open the main XML file.

Paste this code into it.

activity_main.xml
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:padding="10dp"  
  6.     android:orientation="vertical"  
  7.     >  
  8.     <fragment  
  9.        class="com.example.articlefragments.Fragment1"  
  10.        android:id="@+id/fragment1"  
  11.        android:layout_width="match_parent"  
  12.        android:layout_height="wrap_content"  
  13.        android:layout_marginBottom="40dp"/>  
  14.     <Button  
  15.         android:id="@+id/switchFragmentsButton"  
  16.         android:layout_height="wrap_content"  
  17.         android:layout_width="wrap_content"  
  18.         android:layout_gravity="center"  
  19.         android:layout_marginBottom="10dp"  
  20.         android:text="Switch Fragments"/>  
  21.     <FrameLayout  
  22.         android:id="@+id/frameForDynamicFragments"  
  23.         android:layout_width="match_parent"  
  24.         android:layout_height="wrap_content" >  
  25.     </FrameLayout>  
  26. </LinearLayout> 
The <fragment> tag is the static fragment. We cannot replace this fragment with another fragment. We have also added a FrameLayout to hold another fragment. You will see its use later.

2. Now create 3 XML files named fragment1.xml, fragment2.xml and fragment3.xml

fragment1.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="#ABABAB">  
  6.     <TextView  
  7.         android:layout_height="wrap_content"  
  8.         android:layout_width="match_parent"  
  9.         android:text="This is Static Fragment 1"  
  10.         android:textSize="20sp"  
  11.         />  
  12. </LinearLayout> 
fragment2.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="#A1A1A1" >  
  6.     <TextView  
  7.         android:layout_height="wrap_content"  
  8.         android:layout_width="match_parent"  
  9.         android:text="This is text for fragment 2"  
  10.         android:textSize="20sp"  
  11.         android:gravity="center"  
  12.         />  
  13. </LinearLayout> 
fragment3.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="#D1D1D1">  
  6.     <TextView  
  7.         android:layout_height="wrap_content"  
  8.         android:layout_width="match_parent"  
  9.         android:text="This is text for fragment 3"  
  10.         android:textSize="20sp"  
  11.         android:gravity="center"  
  12.         />  
  13. </LinearLayout> 
3. Now create 3 Java files Fragment1.java, Fragment2.java, and Fragment3.java.

Fragment1.java
  1. import android.os.Bundle;  
  2. import android.support.v4.app.Fragment;  
  3. import android.view.LayoutInflater;  
  4. import android.view.View;  
  5. import android.view.ViewGroup;  
  6.   
  7. public class Fragment1 extends Fragment{  
  8.   
  9.     @Override  
  10.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  11.             Bundle savedInstanceState) {  
  12.         // TODO Auto-generated method stub  
  13.           
  14.         View view = inflater.inflate(R.layout.fragment1, container, false);  
  15.           
  16.         return view;  
  17.     }  

Here we have extended the Fragment class from the android.support.v4.app package and overriden the method onCreateView that returns the view for the fragment.
The three files are nearly the same, with just the difference of the layout called i.e. just replace the fragment XML file name "R.layout.fragment2" for "Fragment2.java" and "R.layout.fragment3" for "Fragment3.java".

4. Now open the MainActivity file

MainActivity.java
  1. import android.os.Bundle;  
  2. import android.support.v4.app.FragmentActivity;  
  3. import android.support.v4.app.FragmentManager;  
  4. import android.support.v4.app.FragmentTransaction;  
  5. import android.view.Menu;  
  6. import android.view.View;  
  7. import android.view.View.OnClickListener;  
  8. import android.widget.Button;  
  9.   
  10. //The MainActivity extends FragmentActivity instead of normal Activity class.  
  11. public class MainActivity extends FragmentActivity {  
  12.       
  13.     Fragment2 fragment2;  
  14.     Fragment3 fragment3;  
  15.       
  16.     Boolean isFragment2Showing;  
  17.       
  18.     @Override  
  19.     protected void onCreate(Bundle savedInstanceState) {  
  20.         super.onCreate(savedInstanceState);  
  21.         setContentView(R.layout.activity_main);  
  22.           
  23.           
  24.         //Initialize fragment2 and fragment3  
  25.         fragment2 = new Fragment2();  
  26.         fragment3 = new Fragment3();  
  27.                   
  28.         // Add the fragment to the FrameLayout  
  29.         getSupportFragmentManager().beginTransaction()  
  30.                 .add(R.id.frameForDynamicFragments, fragment2).commit();  
  31.   
  32.         //This means that fragment2 is visible  
  33.         isFragment2Showing = true;  
  34.           
  35.         //Set OnClickListener on button for switching the fragments  
  36.         ((Button)findViewById(R.id.switchFragmentsButton)).setOnClickListener(new OnClickListener() {  
  37.               
  38.             @Override  
  39.             public void onClick(View v) {  
  40.                 // TODO Auto-generated method stub  
  41.                 switchFragments();  
  42.             }  
  43.         });  
  44.     }  
  45.   
  46.     /* 
  47.      * Method to replace fragments with slide animation 
  48.      */  
  49.     private void switchFragments() {  
  50.   
  51.         //Get the supported FragmentManager.  
  52.         //It is used for interaction with the Fragment. Remember that Fragments are only supported after API 11 and we have to add the android-support-v4.jar in project dependencies for backword compatability.  
  53.         FragmentManager   manager         =   getSupportFragmentManager();  
  54.         FragmentTransaction ft            =   manager.beginTransaction();  
  55.           
  56.         //Set the Fragment change animation  
  57.         ft.setCustomAnimations(android.R.anim.slide_in_left , android.R.anim.slide_out_right);  
  58.           
  59.         //If fragment2 is showing then change to fragment3  
  60.         if (isFragment2Showing) {  
  61.               ft.replace(R.id.frameForDynamicFragments, fragment3);  
  62.         }  
  63.         //else back to fragment 2  
  64.         else {  
  65.               ft.replace(R.id.frameForDynamicFragments, fragment2);  
  66.         }  
  67.         ft.commit();  
  68.         isFragment2Showing = !isFragment2Showing;  
  69.     }  
  70.       
  71.     @Override  
  72.     public boolean onCreateOptionsMenu(Menu menu) {  
  73.         // Inflate the menu; this adds items to the action bar if it is present.  
  74.         getMenuInflater().inflate(R.menu.activity_main, menu);  
  75.         return true;  
  76.     }  
  77.   

Please see the comments above the code lines for further explanation.

This should be the final result:


Article2Img1.png 
article2img2
 
 
Official Google documentation on Fragments: http://developer.android.com/reference/android/app/Fragment.html


Similar Articles