动画的定义
对象随着时间来改变自身的大小、时间、位置、方向等。
动画的类型
逐帧动画、补间动画
逐帧动画
有一些类似的图片,按照时间线来展示。
逐帧动画的原理
Android中动画是通过AnimatationDrawable类来实现的,他可以与任何其他的Drawable对象表示Drawable,另外还可以获取其他的Drawable资源用指定的时间来显示。这个类实际上是在Drawable类的动画支持的基础上做的包装。
Drawable实现动画的方式:要求容器或者视图调用Runnable类,该类的实际是使用不同的参数重写绘制Drawable,如果要实现比较复杂的绘画,可以查看AnimationDrawable的源代码。
实现例子
自己弄几个图片,实现一个圆环的效果
步骤:
新建工程
新建一个java类
把资源图片放到Drawable文件家
编写动画xml文件
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false">
<item android:drawable="@drawable/a1" android:duration="50"/>
<item android:drawable="@drawable/a2" android:duration="50"/>
<item android:drawable="@drawable/a3" android:duration="50"/>
<item android:drawable="@drawable/a4" android:duration="50"/>
<item android:drawable="@drawable/a5" android:duration="50"/>
<item android:drawable="@drawable/a6" android:duration="50"/>
</animation-list>
设置布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<Button android:id="@+id/btn_start" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="开始 播放"/>
<Button android:id="@+id/btn_stop" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="停止 播放"/>
<ImageView android:layout_width="fill_parent" android:layout_height="match_parent" android:id="@+id/img_animation_container"/>
</LinearLayout>
关键代码
package cn.edu.fzxy.zxy;
import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class ZhuZhenAnimation extends Activity{
Button btn_start = null;
Button btn_stop = null;
ImageView img_animationContainer = null;
public void onCreate(Bundle b){
super.onCreate(b);
setContentView(R.layout.anitation_layout_1);
btn_start = (Button)findViewById(R.id.btn_start);
btn_stop = (Button)findViewById(R.id.btn_stop);
img_animationContainer = (ImageView)findViewById(R.id.img_animation_container);
btn_start.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
animate();
}
});
btn_stop.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
animate();
}
});
}
protected void animate() {
img_animationContainer.setVisibility(ImageView.VISIBLE);
img_animationContainer.setBackgroundResource(R.drawable.zhuzhen_res);
AnimationDrawable frameAnimation = (AnimationDrawable)img_animationContainer.getBackground();
if(frameAnimation.isRunning()){
frameAnimation.stop();
}else{
frameAnimation.stop();
frameAnimation.start();
}
}
}
效果: