Pages

Friday, December 23, 2011

Android Rotate Animation Example

This tutorial teach you how to use animation and set animation listener

The first you need to have rotate.xml which store in res/anim folder this the picture bellow.


rotate.xml

    


main.xml




this is your refresh drawable image copy it to your res/drawable folder

AnimationExample.java
package montercodz.blogspot.com;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class AnimationExample extends Activity implements OnClickListener {
 private ImageView ivRefresh;
 private Button btnStartAnimation;
 private Button btnStopAnimation;
 private Animation ani;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ivRefresh = (ImageView)findViewById(R.id.ivRefresh);
        btnStartAnimation = (Button)findViewById(R.id.btnRun);
        btnStopAnimation = (Button)findViewById(R.id.btnStop);
        btnStopAnimation.setEnabled(false);
        btnStartAnimation.setOnClickListener(this);
        btnStopAnimation.setOnClickListener(this);
    }
    
    private Animation getRotateAnimation(){
     Animation anim = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
  anim.setInterpolator(new LinearInterpolator());
  return anim;
    }
    
 @Override
 public void onClick(View v) {
  // TODO Auto-generated method stub
  if(v == btnStartAnimation){
   btnStopAnimation.setEnabled(true);
   btnStartAnimation.setEnabled(false);
   ani = getRotateAnimation();
   ani.setAnimationListener(new AnimationListener() {
    
    @Override
    public void onAnimationStart(Animation animation) {
     // TODO Auto-generated method stub
     Toast.makeText(getApplicationContext(), "Animation Start", Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public void onAnimationRepeat(Animation animation) {
     // TODO Auto-generated method stub
     Toast.makeText(getApplicationContext(), "Animation Repeat", Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public void onAnimationEnd(Animation animation) {
     // TODO Auto-generated method stub
     Toast.makeText(getApplicationContext(), "Animation End", Toast.LENGTH_SHORT).show();
    }
   });
   ivRefresh.setAnimation(ani);
  }else if(v == btnStopAnimation){
   btnStartAnimation.setEnabled(true);
   btnStopAnimation.setEnabled(false);
   ivRefresh.clearAnimation();
  }
 }
}
Download source code Click here

No comments:

Post a Comment