版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq77485042/article/details/77834534
安卓中有时候需要使用到帧动画,比如进度条等等。
先在drawable文件夹中建立一个动画文件 “文件名”.xml,其根节点是animation-list
android:oneshot=”false”还需要添加上该属性 取值为boolean值,意思是播放一次还是一直重复。
然后建立多子节点:
drawable属性为资源图,duration属性为该图显示的时长(毫秒值)。
<?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/one"
android:duration="100" />
<item
android:drawable="@drawable/two"
android:duration="100" />
<item
android:drawable="@drawable/three"
android:duration="100" />
<item
android:drawable="@drawable/four"
android:duration="100" />
<item
android:drawable="@drawable/five"
android:duration="100" />
<item
android:drawable="@drawable/six"
android:duration="100" />
<item
android:drawable="@drawable/seven"
android:duration="100" />
</animation-list>
然后在代码中引用该资源文件:
public class Fragment8 extends Fragment {
private ImageView iv;
public AnimationDrawable a;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment8, container, false);
iv = (ImageView) v.findViewById(R.id.iv);
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
iv.setImageResource(R.drawable.anumation);
a = (AnimationDrawable) iv.getDrawable();
a.start();
}
});
return v;
}
点击了imageview后动画就跑起来了。
注意点:(如果需要在activity的一进来时就让动画跑起来的话,不能在OnCreate方法中调用start方法而需要在onWindowFocusChanged方法中调用)
动态使用java代码创建帧动画:
AnimationDrawable frameAnim =new AnimationDrawable();
// 为AnimationDrawable添加动画帧
frameAnim.addFrame(getResources().getDrawable(R.drawable.one), 100);
frameAnim.addFrame(getResources().getDrawable(R.drawable.two), 100);
frameAnim.addFrame(getResources().getDrawable(R.drawable.three), 100);
frameAnim.addFrame(getResources().getDrawable(R.drawable.four), 100);
frameAnim.addFrame(getResources().getDrawable(R.drawable.five), 100);
frameAnim.addFrame(getResources().getDrawable(R.drawable.six), 100);
frameAnim.addFrame(getResources().getDrawable(R.drawable.seven), 100);
// 设置为循环播放
frameAnim.setOneShot(false);
// 设置ImageView设置AnimationDrawable
iv.setImageResource(frameAnim);
frameAnim.start();