我以编程方式创建的 AnimationDrawable
有问题,当我通过 imageView.setBackgroundDrawable
将它分配给 ImageView
时,它就会启动(我支持 API 8)。
这是我的代码的缩写:
mSequence = new AnimationDrawable();
ImageView imageView = new ImageView(context);
ImageView.setAdjustViewBounds(false);
我的所有 Assets 都保存在本地,所以我将它们添加到 AnimationDrawable
for(String assetId : mAssets) {
bitmap = loadBitmap(assetId); // returns a bitmap saved earlier
if (bitmap != null) {
mSequence.addFrame(new BitmapDrawable(res, bitmap), mFrameDuration);
}
}
最后我将 AnimationDrawable
分配给 View
if (mSequence.getNumberOfFrames() > 0) {
imageView.setBackgroundDrawable(mSequence);
}
现在,在我有机会调用 start()
函数之前,动画会在加载 ImageView
后立即开始。
我希望能够按照自己的逻辑控制动画什么时候开始。
有人遇到过这种情况吗?
**
编辑:
**
感谢 Tom,我知道触发动画的原因是在分配 AnimationDrawable
后主动发生的 ImageView
的可见性变化。我的解决方案并不简单,因为我的情况很复杂,但对于其他人来说可能更简单。
编辑 2:
我回到根据 class description 将可绘制对象设置为背景,我引用:
The simplest way to create a frame-by-frame animation is to define the animation in an XML file, placed in the res/drawable/ folder, and set it as the background to a View object. Then, call start() to run the animation.
最佳答案
这很可能是因为您使用 setBackgroundDrawable
将其分配为背景可绘制对象 - 当您分配背景可绘制对象时,对 super.setVisibility 的调用链最终出现在 View 中,并且 setVisible(..)
可以触发动画。
解决方案是使用ImageDrawable吗?
Here's我是如何找到罪魁祸首的。
至于为什么会这样,这可能是一种设计选择,对此我太无知了,无法解释,尽管我明白为什么-它标志着背景和图片之间的区别-前者在概念上更长生命周期,也许。 (但这是一个猜想)。
如果您想使用设置背景的方法,也许可以尝试让您的 ImageViews
不可见,直到您想要显示动画为止。
关于android - AnimationDrawable 自动启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17858462/