Dynamic User Interfaces (Concept Of Fragments)
×
Home Courses Community Support
Gray Matter

First Step Towards Android: Introduction »

Understanding Activities and Intents »

Hands On With UI Designing In Android (Controls-Views,Widgets and Layouts) »

Updating... »

Dynamic User Interfaces (Concept Of Fragments)

Fragments

A Fragment is a piece of an activity which enable more modular activity design. It will not be wrong if we say, a fragment is a kind of sub-activity. There can be more than one fragment in an activity. Fragments represent multiple screen inside one activity.

Following are important points about fragment −

A fragment has its own layout and its own behaviour with its own life cycle callbacks.
Android fragment lifecycle is affected by activity lifecycle because fragments are included in activity.
Each fragment has its own life cycle methods that is affected by activity life cycle because fragments are embedded in activity.
You can add or remove fragments in an activity while the activity is running.
A fragment can be used in multiple activities.
You can combine multiple fragments in a single activity to build a multi-plane UI.
Fragment life cycle is closely related to the life cycle of its host activity which means when the activity is paused, all the fragments available in the activity will also be stopped.
A fragment can implement a behaviour that has no user interface component.
Fragments were added to the Android API in Honeycomb(API 11) version of Android.

You create fragments by extending Fragment class and You can insert a fragment into your activity layout by declaring the fragment in the activity's layout file, as a <fragment> element.

Prior to fragment introduction, we had a limitation because we can show only a single activity on the screen at one given point in time. So we were not able to divide device screen and control different parts separately. But with the introduction of fragment we got more flexibility and removed the limitation of having a single activity on the screen at a time. Now we can have a single activity but each activity can comprise of multiple fragments which will have their own layout, events and complete life cycle.

Following is a typical example of how two UI modules defined by fragments can be combined into one activity for a tablet design, but separated for a handset design.

The application can embed two fragments in Activity A, when running on a tablet-sized device. However, on a handset-sized screen, there's not enough room for both fragments, so Activity A includes only the fragment for the list of articles, and when the user selects an article, it starts Activity B, which includes the second fragment to read the article.

The FragmentManager class is responsible to make interaction between fragment objects.

Fragment Life Cycle

Android fragments have their own life cycle very similar to an android activity. This section briefs different stages of its life cycle. There are 12 lifecycle methods for fragment.

Here is the list of methods which you can to override in your fragment class -

Method Description
onAttach(Activity) it is called only once when it is attached with activity.
The fragment instance is associated with an activity instance.The fragment and the activity is not fully initialized. Typically you get in this method a reference to the activity which uses the fragment for further initialization work.
onCreate(Bundle) It is used to initialize the fragment.
The system calls this method when creating the fragment. You should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.
onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns view hierarchy.
The system calls this callback when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.
onActivityCreated(Bundle) It is invoked after the completion of onCreate() method.
The onActivityCreated() is called after the onCreateView() method when the host activity is created. Activity and fragment instance have been created as well as the view hierarchy of the activity. At this point, view can be accessed with the findViewById() method. example. In this method you can instantiate objects which require a Context object
onViewStateRestored(Bundle) It provides information to the fragment that all the saved state of fragment view hierarchy has been restored.
onStart() makes the fragment visible.
The onStart() method is called once the fragment gets visible.
onResume() makes the fragment interactive.
Fragment becomes active.
onPause() is called when fragment is no longer interactive.
The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session.
onStop() is called when fragment is no longer visible.
Fragment going to be stopped by calling onStop()
onDestroyView() allows the fragment to clean up resources.
Fragment view will destroy after call this method
onDestroy() allows the fragment to do final clean up of fragment state.
onDestroy() called to do final clean up of the fragment's state but Not guaranteed to be called by the Android platform.
onDetach() It is called immediately prior to the fragment no longer being associated with its activity.


How to use Fragments?
This involves number of simple steps to create Fragments.

  • First of all decide how many fragments you want to use in an activity. For example let's we want to use two fragments to handle landscape and portrait modes of the device.
  • Next is, based on number of fragments, create classes which will extend the Fragment class. The Fragment class has above mentioned callback functions. You can override any of the functions based on your requirements.
  • Corresponding to each fragment, you will need to create layout files in XML file. These files will have layout for the defined fragments.
  • Finally modify activity file to define the actual logic of replacing fragments based on your requirement.

Types of Fragments?
Basically fragments are divided as three stages as shown below.

  1. Single frame fragments: Single frame fragments are using for hand hold devices like mobiles, here we can show only one fragment as a view.
  2. List fragments: fragments having special list view is called as list fragment.
  3. Fragments transaction: Using with fragment transaction. we can move one fragment to another fragment.

    We will discuss each type in detail...

Single Frame Fragments:

Single frame fragment is designed for small screen devices such as hand hold devices(mobiles) and it should be above android 3.0 version. To understand it in a better manner let's take an example. Here we will create two fragments and one of them will be used when device is in landscape mode and another fragment will be used in case of portrait mode.

Follow these steps :-

step1: Create a new Android project and name it MyFragments.

step2: Now we will modify MainActivity.java file. So add the following code into MainActivity.java file-

package com.example.myfragments;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.os.Bundle;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.view.WindowManager;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Configuration config = getResources().getConfiguration();

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = 
        fragmentManager.beginTransaction();

        /**
        * Check the device orientation and act accordingly
        */
        if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
           /**
           * Landscape mode of the device
           */
           LM_Fragment ls_fragment = new LM_Fragment();
           fragmentTransaction.replace(android.R.id.content, ls_fragment);
        }else{
           /**
           * Portrait mode of the device
           */
           PM_Fragment pm_fragment = new PM_Fragment();
           fragmentTransaction.replace(android.R.id.content, pm_fragment);
        }
        fragmentTransaction.commit();
    }
    
}


step3: Now Create a new activity. To create a new activity make a right click on your package and then locate New/Other../Android/Android Activity click on it and click Next, then choose Blank Activity and again click on Next. name this activity LM_Fragment and click on Finish. Your new activity has been created. Now we will modify LM_Fragment.java file. So add the following code into LM_Fragment.java file-


package com.example.myfragments;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

@SuppressLint("NewApi") public class LM_Fragment extends Fragment{
	   @Override
	   public View onCreateView(LayoutInflater inflater,
	      ViewGroup container, Bundle savedInstanceState) {
	      /**
	       * Inflate the layout for this fragment
	       */
	      return inflater.inflate(
	      R.layout.activity_lm__fragment, container, false);
	}


}


step4: Now Create a new activity. To create a new activity make a right click on your package and then locate New/Other../Android/Android Activity click on it and click Next, then choose Blank Activity and again click on Next. name this activity PM_Fragment and click on Finish. Your new activity has been created. Now we will modify PM_Fragement.java file. So add the following code into PM_Fragement.java file-

package com.example.myfragments;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

@SuppressLint("NewApi") public class PM_Fragment extends Fragment{
	   @Override
	   public View onCreateView(LayoutInflater inflater,
	      ViewGroup container, Bundle savedInstanceState) {
	      /**
	       * Inflate the layout for this fragment
	       */
	      return inflater.inflate(
	      R.layout.activity_pm__fragment, container, false);
	}

}


step5: Now we will modify activity_lm_fragment.xml file. So add the following code into activity_lm_fragment.xml file-

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
	android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#7bae16"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".LM_Fragment" >
       <TextView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="@string/landscape_message"
      android:textColor="#000000"
      android:textSize="20px" />
    

</LinearLayout>


step6: Now we will modify activity_pm_fragment.xml file. So add the following code into activity_pm_fragment.xml file-

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#666666"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".PM_Fragment" >
    
       <TextView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="@string/portrait_message"
      android:textColor="#000000"
      android:textSize="20px" />

</LinearLayout>


step7: Now we will modify activity_main.xml file. So add the following code into activity_main.xml file-

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
   	android:layout_width="fill_parent"
   	android:layout_height="fill_parent"
  	android:orientation="horizontal"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    
       <fragment
      android:name="com.example.fragments"
      android:id="@+id/lm_fragment"
      android:layout_weight="1"
      android:layout_width="0dp"
      android:layout_height="match_parent" />
   
   <fragment
      android:name="com.example.fragments"
      android:id="@+id/pm_fragment"
      android:layout_weight="2"
      android:layout_width="0dp"
      android:layout_height="match_parent" />
    

</LinearLayout>


step8: Now we will modify strings.xml file which is situated at res/values directory. So add the following code into strings.xml file-

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">MyFragments</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="title_activity_lm__fragment">LM_Fragment</string>
    <string name="title_activity_pm__fragment">PM_Fragment</string>
    <string name="landscape_message">This is Landscape mode fragment</string>
   	<string name="portrait_message">This is Portrait mode fragment></string>

</resources>


step9: Now Press F11 key to debug the application on the Android Emulator or on the device. Let's see the output window now.


 

To change the mode of the emulator screen, let's do the following −

  • fn+control+F11 on Mac to change the landscape to portrait and vice versa.
  • ctrl+F11 on Windows.
  • ctrl+F11 on Linux.
  • Once you changed the mode, you will be able to see the GUI which you have implemented for landscape mode as below −

In this way you can use same activity but different GUI's through different fragments. You can use different type of GUI components for different GUI's based on your requirements.


List Fragments:

Static library support version of the framework's ListFragment. Used to write apps that run on platforms prior to Android 3.0. When running on Android 3.0 or above, this implementation is still used.

The basic implementation of list fragment is for creating list of items in fragments.

To understand it in a better manner let's take an example.
Follow these steps :-

step1: Create a new Android project and name it SimpleListFragment.

step2: Now we will modify strings.xml file which is situated at res/values directory. So add the following code into strings.xml file-

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">SimpleListFragment</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    
    <string name="imgdesc">imgdesc</string>
   
   <string-array name="Planets">
      <item>Sun</item>
      <item>Mercury</item>
      <item>Venus</item>
      <item>Earth</item>
      <item>Mars</item>
      <item>Jupiter</item>
      <item>Saturn</item>
      <item>Uranus</item>
      <item>Neptune</item>
   </string-array>

</resources>


step3: Now we will modify activity_main.xml file. So add the following code into activity_main.xml file-

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <fragment
        android:id="@+id/fragment1"
        android:name="android.app.ListFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>


step4: Now Create a new XML file. To create a new XML file make a right click on layout under res directory and then locate New/Other../Android/Android XML File, click on it and click Next, then name it list_fragment and click on Finish. Your new XML file has been created. Now we will modify list_fragment.xml file. So add the following code into list_fragment.xml file-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
     xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

    <TextView
        android:id="@android:id/empty"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </TextView>

</LinearLayout>


step5: Now Create a new java file. To create a new java file make a right click on on your package and then locate New/Class, click on it , then name it myListFragment.java and click on Finish. Your new java file has been created. Now we will modify myListFragment.java file. So add the following code into myListFragment.java file-

package com.example.simplelistfragment;
import android.annotation.SuppressLint;
import android.app.ListFragment;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Toast;


@SuppressLint("NewApi") public class myListFragment extends ListFragment implements OnItemClickListener {
	   @Override
	   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
	      View view = inflater.inflate(R.layout.list_fragment, container, false);
	      return view;
	   }
	   
	   @Override
	   public void onActivityCreated(Bundle savedInstanceState) {
	      super.onActivityCreated(savedInstanceState);
	      ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.Planets, android.R.layout.simple_list_item_1);
	      setListAdapter(adapter);
	      getListView().setOnItemClickListener(this);
	   }
	   
	   @Override
	   public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
	      Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
	   }
	}


step6: Now we will modify MainActivity.java file. So add the following code into MainActivity.java file-

package com.example.simplelistfragment;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}


step7: Now we will modify Manifest.xml file. So add the following code into AndroidManifest.xml file-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.simplelistfragment"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.simplelistfragment.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


step8: Now Press F11 key to debug the application on the Android Emulator or on the device. Let's see the output window now.

 

 


Fragment Transition:

What is a transition?

Activity and Fragment transitions in Lollipop are built on top of a relatively new feature in Android called Transitions. Introduced in KitKat, the transition framework provides a convenient API for animating between different UI states in an application. The framework is built around two key concepts: scenes and transitions. A scene defines a given state of an application's UI, whereas a transition defines the animated change between two scenes.

When a scene changes, a Transition has two main responsibilities −

  • Capture the state of each view in both the start and end scenes.
  • Create an Animator based on the differences that will animate the views from one scene to the other.

To understand it in a better manner let's take an example.
Follow these steps :-

step1: Create a new Android project and name it fragmentcustomanimations.

step2: Now we will modify activity_main.xml file. So add the following code into activity_main.xml file-

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/text"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:gravity="center_vertical|center_horizontal"
   android:text="@string/hello_world"
   android:textAppearance="?android:attr/textAppearanceMedium" />


step3: Now Create a new XML file. To create a new XML file make a right click on layout under res directory and then locate New/Other../Android/Android XML File, click on it and click Next, then name it fragment_stack and click on Finish. Your new XML file has been created. Now we will modify fragment_stack.xml file. So add the following code into fragment_stack.xml file-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical" >
   
   <fragment
      android:id="@+id/fragment1"
      android:name="com.pavan.listfragmentdemo.MyListFragment"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />

</LinearLayout>


step4: Now Create a new XML file. To create a new XML file make a right click on animation under res directory and then locate New/Other../Android/Android XML File, click on it and click Next, then name it fragment_slide_left_enter and click on Finish. Your new XML file has been created. Now we will modify fragment_slide_left_enter.xml file. So add the following code into fragment_slide_left_enter file-

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
   <objectAnimator
      android:interpolator="@android:interpolator/decelerate_quint"
      android:valueFrom="100dp" android:valueTo="0dp"
      android:valueType="floatType"
      android:propertyName="translationX"
      android:duration="@android:integer/config_mediumAnimTime" />
   
   <objectAnimator
      android:interpolator="@android:interpolator/decelerate_quint"
      android:valueFrom="0.0" android:valueTo="1.0"
      android:valueType="floatType"
      android:propertyName="alpha"
      android:duration="@android:integer/config_mediumAnimTime" />
</set>


step4: Now Create a new XML file. To create a new XML file make a right click on animation under res directory and then locate New/Other../Android/Android XML File, click on it and click Next, then name it fragment_slide_left_exit and click on Finish. Your new XML file has been created. Now we will modify fragment_slide_left_exit.xml file. So add the following code into fragment_slide_left_exit file-

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
   <objectAnimator
      android:interpolator="@android:interpolator/decelerate_quint"
      android:valueFrom="0dp" android:valueTo="-100dp"
      android:valueType="floatType"
      android:propertyName="translationX"
      android:duration="@android:integer/config_mediumAnimTime" />
   
   <objectAnimator
      android:interpolator="@android:interpolator/decelerate_quint"
      android:valueFrom="1.0" android:valueTo="0.0"
      android:valueType="floatType"
      android:propertyName="alpha"
      android:duration="@android:integer/config_mediumAnimTime" />


step4: Now Create a new XML file. To create a new XML file make a right click on animation under res directory and then locate New/Other../Android/Android XML File, click on it and click Next, then name it fragment_slide_right_enter and click on Finish. Your new XML file has been created. Now we will modify fragment_slide_right_enter.xml file. So add the following code into fragment_slide_right_enter file-

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="-100dp" android:valueTo="0dp"
        android:valueType="floatType"
        android:propertyName="translationX"
        android:duration="@android:integer/config_mediumAnimTime" />
   
   <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="0.0" android:valueTo="1.0"
        android:valueType="floatType"
        android:propertyName="alpha"
        android:duration="@android:integer/config_mediumAnimTime" />
</set>


step4: Now Create a new XML file. To create a new XML file make a right click on animation under res directory and then locate New/Other../Android/Android XML File, click on it and click Next, then name it fragment_slide_right_exit and click on Finish. Your new XML file has been created. Now we will modify fragment_slide_right_exit.xml file. So add the following code into fragment_slide_right_exit file-

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="0dp" android:valueTo="100dp"
        android:valueType="floatType"
        android:propertyName="translationX"
        android:duration="@android:integer/config_mediumAnimTime" />
    
    <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="1.0" android:valueTo="0.0"
        android:valueType="floatType"
        android:propertyName="alpha"
        android:duration="@android:integer/config_mediumAnimTime" />
</set>


step5: Create a folder, To create a new folder make a right click on res directory and then locate New/Folder and name it animation

step6: Now we will modify MainActivity.java file. So add the following code into MainActivity.java file-

package com.example.fragmentcustomanimations;
 
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;

import android.widget.Button;
import android.widget.TextView;
 
/**
 * Demonstrates the use of custom animations in a FragmentTransaction when
 * pushing and popping a stack.
 */
public class FragmentCustomAnimations extends Activity {
   int mStackLevel = 1;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.fragment_stack);
      
      // Watch for button clicks.
      Button button = (Button)findViewById(R.id.new_fragment);
      
      button.setOnClickListener(new OnClickListener() {
         public void onClick(View v) {
            addFragmentToStack();
         }
      });
      
      if (savedInstanceState == null) {
         // Do first time initialization -- add initial fragment.
         Fragment newFragment = CountingFragment.newInstance(mStackLevel);
         FragmentTransaction ft = getFragmentManager().beginTransaction();
         ft.add(R.id.simple_fragment, newFragment).commit();
      }
      else
      {
         mStackLevel = savedInstanceState.getInt("level");
      }
   }
   
   @Override
   public void onSaveInstanceState(Bundle outState) {
      super.onSaveInstanceState(outState);
      outState.putInt("level", mStackLevel);
   }
   
   void addFragmentToStack() {
      mStackLevel++;
   
      // Instantiate a new fragment.
      Fragment newFragment = CountingFragment.newInstance(mStackLevel);
   
      // Add the fragment to the activity, pushing this transaction
      // on to the back stack.
      FragmentTransaction ft = getFragmentManager().beginTransaction();
      ft.setCustomAnimations(R.animator.fragment_slide_left_enter,
      R.animator.fragment_slide_left_exit,
      R.animator.fragment_slide_right_enter,
      R.animator.fragment_slide_right_exit);
      ft.replace(R.id.simple_fragment, newFragment);
      ft.addToBackStack(null);
      ft.commit();
   }
   
   public static class CountingFragment extends Fragment {
      int mNum;
      /**
      * Create a new instance of CountingFragment, providing "num"
      * as an argument.
      */
      static CountingFragment newInstance(int num) {
         CountingFragment f = new CountingFragment();
          
         // Supply num input as an argument.
         Bundle args = new Bundle();
         args.putInt("num", num);
         f.setArguments(args);
         return f;
      }
      
      /**
      * When creating, retrieve this instance's number from its arguments.
      */
      @Override
      public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         mNum = getArguments() != null ? getArguments().getInt("num") : 1;
      }
      /**
      * The Fragment's UI is just a simple text view showing its
      * instance number.
      */
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
         View v = inflater.inflate(R.layout.hello_world, container, false);
         View tv = v.findViewById(R.id.text);
         ((TextView)tv).setText("Fragment #" + mNum);
         tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
         return v;
      }
   }
}


step7: Now we will modify Manifest.xml file. So add the following code into AndroidManifest.xml file-

<?xml version="1.0" encoding="utf-8"?>
   <manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.fragmentcustomanimations"
   android:versionCode="1"
   android:versionName="1.0" >
   
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
         
      <activity
         android:name="com.example.fragmentcustomanimations.MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
         
   </application>
</manifest>


step8: Now Press F11 key to debug the application on the Android Emulator or on the device. Let's see the output window now.


 

If you will click on new fragment, it is going to be changed the first fragment to second fragment as shown below-



 

← Preview

UI Notification Listeners

Next →

Support For Multiple Screen

NOTES

Our mission is to provide highly effective and quality education via innovative solutions. Geeksdemy look forward to bridge the gap between in-demand technology and academics in order to deliver innovative, easy, interesting and affordable learning across the Globe.

Courses

  • Python
  • Game Development with Unity 3D
  • Arduino
  • PCB & Circuit Designing
  • Robotics and Embedded C
  • 8051/8052 Embedded Systems
  • QuadCopter & UAV
  • MATLAB with Robotics
  • Raspberry Pi
Learn On the Go!
Get the Android App
Get the iOS App