Runoob Tutorial ArchiveEnglish

Android Fragment Transitions

Android Fragment Transitions

Activity and Fragment transitions in Lollipop (Android 5.0) are built upon some relatively new Android features called Transitions. Introduced in KitKat, the Transition framework provides a set of convenient APIs to provide animations between different UI states of an application. This framework is built around two key concepts: Scenes and Transitions. A Scene defines a given state of the application UI, and a Transition defines the animated change between two Scenes.

When a Scene changes, a Transition has two main responsibilities:


Instance

This instance explains how to use Fragment Transitions to create custom animations. Let's start with the following steps:

Steps Description
1 Use Android Studio to create an Android application named Fragment Custom Animation, with the package name cn.uprogrammer.fragmentcustomanimation.
2 Modify the res/layout/activity_main.xml file to add a TextView
3 Create the layout file fragment_stack.xml in res/layout/ to define the fragment tag and button tag
4 Create a subdirectory anim in res/ and add fragment_slide_left.xml, fragment_slide_left_exit.xml, fragment_slide_right_exit.xml, and fragment_slide_left_enter.xml
5 You need to add the fragment stack, fragment manager, and onCreateView() in MainActivity.java
6 Start the Android emulator to run the application and verify the results of the changes made to the application.

The content of res/layout/activity_main.xml is as follows, which includes a FrameLayout and buttons.

Original prompt (Chinese, left untranslated)

<?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" >



    <FrameLayout

        android:id="@+id/fragment1"

        android:layout_width="match_parent"

        android:layout_height="0dp"

        android:layout_weight="1" />



    <Button

        android:id="@+id/new_fragment"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Add new fragment" />



</LinearLayout>

The res/anim/fragment_stack.xml file is as follows:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical" android:layout_width="match_parent"

    android:layout_height="match_parent">

    <TextView

        android:id="@+id/text"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:gravity="center"/>

</LinearLayout>

Below is the content of res/animator/fragment_slide_left_enter.xml, which contains method setting and animator object tags.

<?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>

Below is the content of res/animator/fragment_slide_left_exit.xml, which contains method setting and animator object tags.

<?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>

Below is the content of res/animator/fragment_slide_right_enter.xml, which contains method setting and animator object tags.

<?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>

Below is the content of res/animator/fragment_slide_right_exit.xml, which contains method setting and animator object tags.

<?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>

Below is the content of src/cn.uprogrammer.fragmentcustomanimation/MainActivity.java, which contains button listeners, CountingFragment, and onCreateView():

Original prompt (Chinese, left untranslated)

package cn.uprogrammer.fragmentcustomanimation;



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;



/**

 * Demonstrate using custom animations in fragmented transactions.

 */

public class MainActivity extends Activity {

    int mStackLevel = 1;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        Button button = (Button)findViewById(R.id.new_fragment);



        button.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                addFragmentToStack();

            }

        });



        if (savedInstanceState == null) {

            // Add initial fragments

            Fragment newFragment = CountingFragment.newInstance(mStackLevel);

            FragmentTransaction ft = getFragmentManager().beginTransaction();

            ft.add(R.id.fragment1, 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 fragment to activity, and put it into 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.fragment1, newFragment);

        ft.addToBackStack(null);

        ft.commit();

    }



    public static class CountingFragment extends Fragment {

        int mNum;

        /**

         // Create an instance of CountingFragment, providing "num" as a parameter

         */

        static CountingFragment newInstance(int num) {

            CountingFragment f = new CountingFragment();



            Bundle args = new Bundle();

            args.putInt("num", num);

            f.setArguments(args);

            return f;

        }



        /**

         * When creating, get the instance's number parameter.

         */

        @Override

        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            mNum = getArguments() != null ? getArguments().getInt("num") : 1;

        }

        /**

         * The fragment's interface only contains a TextView, used to display the number

         */

        @Override

        public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

            View v = inflater.inflate(R.layout.fragment_stack, 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;

        }

    }

}

Below is the content of AndroidManifest.xml:

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="cn.uprogrammer.fragmentcustomanimation"

    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=".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>

Let's run the Fragment Custom Animation application that was just modified. I assume you have created an AVD during the installation environment setup. Open the activity file in your project and click the icon in the toolbar to run the application in Android Studio. Android Studio installs and launches the application on the AVD. If everything goes well, it will display as follows on the emulator window:PictureUse the icon to run the application in Android Studio. Android Studio installs and launches the application on the AVD. If everything goes well, it will be displayed in the emulator window as follows:

image