Thursday, November 24, 2011

Animation Part 1

In this post I show how to create Animation in android.
Create a folder "anim" in your project "res" folder. Create a new xml (translate.xml) file in anim folder, select the root element as translate.
Write the following code in your translate.xml file

translate.xml

<?xml version="1.0" encoding="utf-8"?>
<translate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="200%"
    android:toXDelta="0%"
    android:fromYDelta="200%"
    android:toYDelta="0%"
    android:duration="3000"
    android:zAdjustment="top">
</translate>

Open your main.xml file, add a TextView.

main.xml 

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

    <TextView
        android:id="@+id/t1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Welcome"
        android:gravity="center_horizontal"
        android:textSize="30sp" />

</LinearLayout>

Open your Activity file and write the following code.

AnimationActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;

public class AnimationActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
 private void RunAnimation()
    {
        Animation a=AnimationUtils.loadAnimation(this, R.anim.translate);
        a.reset();
        TextView tv=(TextView)findViewById(R.id.t1);
        tv.clearAnimation();
        tv.startAnimation(a);
   }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction()==MotionEvent.ACTION_DOWN)
        {
            RunAnimation();
        }
        return true;
    }
}

Run your project.

No comments:

Post a Comment