AnimationDrawable的源码学习
[TOC]
文章参考:https://binkery.com/archives/523.html
https://dandanlove.com/2018/05/02/Android-animation-source/
https://www.jianshu.com/p/c0057afb0c79
https://blog.csdn.net/qq_36467463/article/details/79423824
概述
AnimationDrawable源码
AnimationDrawable的用法如下:
1 | public void onCreate(Bundle savedInstanceState) { |
事实上,在onCreate()方法中调用AnimationDrawable.start()是无效的。看官方文档的解释:
1 | It's important to note that the start() method called on the AnimationDrawable cannot be called during the onCreate() method of your Activity, because the AnimationDrawable is not yet fully attached to the window. If you want to play the animation immediately, without requiring interaction, then you might want to call it from the onWindowFocusChanged() method in your Activity, which will get called when Android brings your window into focus. |
大意是,在onCreate
方法中,AnimationDrawable
没有完全关联到Window
,这时调用start()
方法是没有用的。需要在onWindowFocusChanged()
方法中调用。
但令人费解的是,我尝试在onCreate()
方法中调用了AnimationDrawable.start()
方法,发现帧动画的确启动了。按照文档的说法应该是不会启动的。
Drawable的内存问题
AnimationDrawable
会一次性把所有图片加载到内存中,在某些内存吃紧的设备上会出现OOM的问题OutOfMemoryError
。
Bitmap
是内存杀手,而AnimationDrawable
则会一次性将所有用到的图片全部加载到内存中,很容易就会导致OutOfMemoryError
。可以说是Bitmap
的帮凶。
这个问题并不是必现的,只有在特定的机型上才会出现。所以这也增加了其隐蔽性。
Animation的使用方式
1、通过XML文件方式
AnimationDrawable
继承自Drawable
。我们是通过xml
文件保存帧动画信息的,所以从Drawable.createFromXml()
方法看起: