注意:
有时动画会出现停留在第一帧不播放的情况。
是因为window还没有加载好。
所以最好这样:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
initViews();// 要执行的动画方法
super.onWindowFocusChanged(hasFocus);
}
第一种: Xml
①:
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="true">
<item android:drawable="@drawable/splash01" android:duration="3000" />
<item android:drawable="@drawable/splash02" android:duration="3000" />
<item android:drawable="@drawable/splash03" android:duration="3000" />
</animation-list>
看看内容应该是很好理解的,<animation-list>为动画的总标签,这里面放着帧动画 <item>标签,也就是说若干<item>标签的帧 组合在一起就是帧动画了。<animation-list > 标签中android:oneshot="false" 这是一个非常重要的属性,默认为false 表示 动画循环播放, 如果这里写true 则表示动画只播发一次。 <item>标签中记录着每一帧的信息android:drawable="@drawable/a"表示这一帧用的图片为"a",下面以此类推。 android:duration="100" 表示这一帧持续100毫秒,可以根据这个值来调节动画播放的速度。
②:
拿到布局文件中的ImageView
imageView.setBackgroundResource(R.drawable.animation);
/**通过ImageView对象拿到背景显示的AnimationDrawable
animationDrawable = (AnimationDrawable) imageView.getBackground();
③:
animationDrawable.start(); 开始这个动画
animationDrawable.stop(); 结束这个动画
animationDrawable.setAlpha(100);设置动画的透明度, 取值范围(0 - 255)
animationDrawable.setOneShot(true); 设置单次播放
animationDrawable.setOneShot(false); 设置循环播放
animationDrawable.isRunning(); 判断动画是否正在播放
animationDrawable.getNumberOfFrames(); 得到动画的帧数
第二种: 从SD卡加载图片
①:
ImageView view = (ImageView) findViewById(R.id.splash_anim);
AnimationDrawable d = new AnimationDrawable();
view.setImageDrawable(d);
AnimationDrawable animationDrawable = (AnimationDrawable)view.getDrawable();
②:
ArrayList<Bitmap> list = new ArrayList<Bitmap>();
Bitmap bitmap = getImageFromLocal("splash01.jpg");
Bitmap bitma = getImageFromLocal("splash02.png");
Bitmap bitm = getImageFromLocal("splash03.png");
Log.i("animationDrawable", "图片在添加转化为bitmap");
Log.i("animationDrawable", "animationDrawable是否为空:"+(animationDrawable==null));
animationDrawable.addFrame(new BitmapDrawable(bitmap), 1000);
animationDrawable.addFrame(new BitmapDrawable(bitma), 1000);
animationDrawable.addFrame(new BitmapDrawable(bitm), 2000);
③:
animationDrawable.start();
/**
* 从SD卡加载图片
*
* @param imagePath
* @return
*/
public Bitmap getImageFromLocal(String name) {
String imagePath = "/mnt/sdcard/" + name;
File file = new File(imagePath);
if (file.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
file.setLastModified(System.currentTimeMillis());
return bitmap;
}
return null;
}