Thursday, 15 August 2013

Android Animation Using XML

In this post i am going to show you how to do animation using XML Notation and in my next post i am going to show you how to do animation using android code.

For now i will only show rotation example.

So first of all create an folder in res/ folder and name it anim as shown in image below.


Now create rotate.xml file inside anim folder and past the following code into that file.


<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
   
    <rotate android:fromDegrees="0"
        android:toDegrees="360"
        android:pivotX="50%"
        android:pivotY="50%"
        android:repeatMode="restart"
        android:repeatCount="infinite"
        android:duration="600"
        android:interpolator="@android:anim/cycle_interpolator"/>

</set>
 

Now Load the animation in you activity.


public class RotateActivity extends Activity{

    TextView txtMessage;

    // Animation
    Animation animRotate;

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

        txtMessage = (TextView) findViewById(R.id.txtMessage);

        // load the animation
        animRotate = AnimationUtils.loadAnimation(getApplicationContext(),
                R.anim.rotate);       
    }
}

Finally start the animation using following code.


// start the animation
txtMessage.startAnimation(animRotate);

Similarly you can create xml files for other animations too and can use in your activity.