一、通过xml文件设置
1.配置drawable里的xml文件
frameanim.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/background" android:duration="100"/>
<item android:drawable="@drawable/poke_belly_right_0001" android:duration="100"/>
<item android:drawable="@drawable/poke_belly_right_0002" android:duration="100"/>
<item android:drawable="@drawable/poke_belly_right_0003" android:duration="100"/>
<item android:drawable="@drawable/poke_belly_right_0004" android:duration="100"/>
<item android:drawable="@drawable/poke_belly_right_0005" android:duration="100"/>
<item android:drawable="@drawable/poke_belly_right_0006" android:duration="100"/>
<item android:drawable="@drawable/poke_belly_right_0007" android:duration="100"/>
<item android:drawable="@drawable/poke_belly_right_0008" android:duration="100"/>
<item android:drawable="@drawable/background" android:duration="100"/>
</animation-list>
2.为控件添加动画文件src
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/p_w_picpathView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="@drawable/frameanim" />
</RelativeLayout>
3.代码里的实现方法:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView ivTom = (ImageView) findViewById(R.id.p_w_picpathView1);
final AnimationDrawable drawable = (AnimationDrawable) ivTom.getDrawable();//转换类型
ivTom.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
drawable.stop();//每次播放前都先让动画恢复,否则播放一次后会停在最后一帧
drawable.start();
}
});
}
其他写法:
iv.setBackgroundResource(R.drawable.anim);
AnimationDrawable an=(AnimationDrawable)iv.getBackground();
an.start();
iv.setBackgroundResource(R.drawable.anim);
AnimationDrawable an=(AnimationDrawable)iv.getBackground();
an.start();
========================其他方法=====================
然后新建一个AnimationDrawable对象,把这些图片加载进去。 addFrame第一参数表示要加载的内容,第二参数表示持续时间。
代码:
1. frameAnimation = new AnimationDrawable();
2. for (int i = 0; i < 10; i++) {
3. int id = getResources().getIdentifier("load" + (i+1), "drawable", this.getContext().getPackageName());
4. frameAnimation.addFrame(getResources().getDrawable(id), 100);
5. }
6.
7. //设置循环播放 false表示循环 true表示不循环,仅播放一次
8. frameAnimation.setOneShot(false);
AnimationDrawable 类是Drawable类的子类,因此可以将 AnimationDrawable 设为背景等来查看效果。
最后只要调用 frameAnimation.start(); 就可以启动该Frame动画了。
转载于:https://blog.51cto.com/glblong/1225369