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. public class Fragment1 extends Fragment{
  7. @Override
  8. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  9. Bundle savedInstanceState) {
  10. // TODO Auto-generated method stub
  11. View view = inflater.inflate(R.layout.fragment1, container, false);
  12. return view;
  13. }
  14. }
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. //The MainActivity extends FragmentActivity instead of normal Activity class.
  10. public class MainActivity extends FragmentActivity {
  11. Fragment2 fragment2;
  12. Fragment3 fragment3;
  13. Boolean isFragment2Showing;
  14. @Override
  15. protected void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. setContentView(R.layout.activity_main);
  18. //Initialize fragment2 and fragment3
  19. fragment2 = new Fragment2();
  20. fragment3 = new Fragment3();
  21. // Add the fragment to the FrameLayout
  22. getSupportFragmentManager().beginTransaction()
  23. .add(R.id.frameForDynamicFragments, fragment2).commit();
  24. //This means that fragment2 is visible
  25. isFragment2Showing = true;
  26. //Set OnClickListener on button for switching the fragments
  27. ((Button)findViewById(R.id.switchFragmentsButton)).setOnClickListener(new OnClickListener() {
  28. @Override
  29. public void onClick(View v) {
  30. // TODO Auto-generated method stub
  31. switchFragments();
  32. }
  33. });
  34. }
  35. /*
  36. * Method to replace fragments with slide animation
  37. */
  38. private void switchFragments() {
  39. //Get the supported FragmentManager.
  40. //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.
  41. FragmentManager manager = getSupportFragmentManager();
  42. FragmentTransaction ft = manager.beginTransaction();
  43. //Set the Fragment change animation
  44. ft.setCustomAnimations(android.R.anim.slide_in_left , android.R.anim.slide_out_right);
  45. //If fragment2 is showing then change to fragment3
  46. if (isFragment2Showing) {
  47. ft.replace(R.id.frameForDynamicFragments, fragment3);
  48. }
  49. //else back to fragment 2
  50. else {
  51. ft.replace(R.id.frameForDynamicFragments, fragment2);
  52. }
  53. ft.commit();
  54. isFragment2Showing = !isFragment2Showing;
  55. }
  56. @Override
  57. public boolean onCreateOptionsMenu(Menu menu) {
  58. // Inflate the menu; this adds items to the action bar if it is present.
  59. getMenuInflater().inflate(R.menu.activity_main, menu);
  60. return true;
  61. }
  62. }
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