Android-动画-帧动画

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ITxiaodong/article/details/80723150

帧动画就像放幻灯片一样。创建的文件推荐存放在 res/drawable 目录下。

帧动画

语法

<animation-list
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:oneshor="true"  : true 表示只执行一次,false 表示循环执行
  >
  <item>
    每一帧的动画资源
    android:drawable="drawable name " : 资源文件
    android:duration="1000"           : 一帧显示多长时间
  </item>
</animation-list>

实例:循环播放几张图片

主页布局:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".AnimDrawableActivity">
    <ImageView
        android:id="@+id/anim_drawable_iv"
        android:layout_width="200dp"
        android:layout_height="200dp"/>
</android.support.constraint.ConstraintLayout>

动画文件:anim_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/ic_menu_camera"
          android:duration="200"/>
    <item android:drawable="@drawable/ic_menu_gallery"
          android:duration="200"/>
    <item android:drawable="@drawable/ic_menu_share"
          android:duration="200"/>
</animation-list>

Java 中调用:

ImageView animDrawable = findViewById(R.id.anim_drawable_iv) ;
animDrawable.setBackgroundResource(R.drawable.anim_drawable);
AnimationDrawable animationDrawable = (AnimationDrawable) animDrawable.getBackground();
animationDrawable.start();

使用帧动画注意事项

AnimationDrawable 的start() 方法不能在activity的 onCreat() 中调用, 因为 AnimationDrawable 还未完全附着到window上, 所以最好的调用时机时在 Activity 的 onWindowFocusChange()方法中。onWindowFocusChange()方法在 Activity 生命周期中表示 view 的可视,onStart, onResume, onCreate 都不是真正 view visible 的时间点,真正的view visible时间点是 onWindowFocusChanged() 函数被执行时。通过下面的执行流程可以清楚了解到 AnimationDrawable 的使用时机。

  • 启动:
 onStart---->onResume---->
 onAttachedToWindow------>
 onWindowVisibilityChanged--visibility=0---------->
 onWindowFocusChanged(true)------->
  • 锁屏:
onPause---->onStop---->
onWindowFocusChanged(false)----------->(lockscreen)
  • 进入下一个页面 :
onPause----->onWindowFocusChanged(false)------>
onWindowVisibilityChanged----visibility=8------------>
onStop(to another activity)

源码地址

猜你喜欢

转载自blog.csdn.net/ITxiaodong/article/details/80723150