Coding Tips: How to Use Custom Transition Animation in Android

Android has a set of Animation API that makes you easily create custom animations in your Android application. You can create animations programmatically via Java code or defined them in xml files inside /res/anim folder. Using your custom animation, you can override the default transition animation between activities to make your app looks more elegant. Overriding the default transition animation is easy, just create two custom animations and call the overridePendingTransition method of Activity class to use them.

How to use custom transition animation:

  • Create two animation files (xml), one for incoming activity (/anim/incoming.xml) and one for outgoing activity (/anim/outgoing.xml).
    Android Transition Animationincoming.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android">
    
    	<translate
    		android:interpolator="@android:anim/accelerate_interpolator"
            android:fromXDelta="0"
            android:toXDelta="0"
            android:duration="300"/>
    
        <scale
    	    android:pivotX="50%"
    	    android:pivotY="50%"
    	    android:fromXScale="0"
    	    android:fromYScale="0"
    	    android:toXScale="1.0"
    	    android:toYScale="1.0"
    	    android:startOffset="300"
    	    android:duration="300" />
    </set>
    

    outgoing.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android">
    
    	<translate
            android:fromXDelta="0"
            android:toXDelta="-50%p"
            android:duration="300" />
    
        <scale
    	    android:pivotX="50%"
    	    android:pivotY="50%"
    	    android:fromXScale="1.0"
    	    android:fromYScale="1.0"
    	    android:toXScale=".1"
    	    android:toYScale=".1"
    	    android:startOffset="300"
    	    android:duration="400" />
    </set>
    
  • Call method overridePendingTransition (int enterAnim, int exitAnim) right after startActivity(intent) to override default transition animation between current activity and next activity.
    Intent intent = new Intent(this, NextActivity.class);
    
    startActivity(intent);
    overridePendingTransition (R.anim.incoming, R.anim.outgoing)
    
  • To use custom transition animation between current activity and previous activity (when user press the back key to get back to previous activity) override the onBackPressed () method and call the overridePendingTransition (int enterAnim, int exitAnim) method. 
    @Override
    public void onBackPressed() {
      super.onBackPressed();
      overridePendingTransition(R.anim.customanim1, R.anim.customanim2)
    }
    
facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *