【问题标题】:Android AnimationDrawable Recycling issueAndroid AnimationDrawable 回收问题
【发布时间】:2015-09-08 17:23:32
【问题描述】:

我有一个 AnimationDrawable,我在开始动画之前初始化它并在它完成时立即回收它。问题是当我想再次启动动画时,我重新初始化所有内容但仍然给出异常

java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@2bbad018

这是我的代码

 public ImageView radarImageView;
 public AnimationDrawable animationDrawable;

    public void animationStart() {

//        animationStop();

        radarImageView = (ImageView) findViewById(R.id.radarIV);
        radarImageView.setBackgroundResource(R.drawable.sensor_animation);
        animationDrawable = (AnimationDrawable) radarImageView.getBackground();

        animationDrawable.start();
    }

    public void animationStop() {

        animationDrawable.stop();

        for (int i = 0; i < animationDrawable.getNumberOfFrames(); ++i){
            Drawable frame = animationDrawable.getFrame(i);
            if (frame instanceof BitmapDrawable) {
                ((BitmapDrawable)frame).getBitmap().recycle();
            }
            frame.setCallback(null);
        }
        animationDrawable.setCallback(null);

//        animationDrawable = null;
//        radarImageView.setBackgroundResource(0);
    }

为什么它不再重新初始化整个东西?

【问题讨论】:

  • 为什么需要回收位图?打电话给animationDrawable.stop() 还不够吗?
  • stop() 不会释放内存.. 这就是为什么我需要调用 recycel
  • 问题在于,当您在位图上调用回收时,您无法重复使用它。并且因为您正在调用setBackgroundResources(R.drawable. sensor_animation),所以您指的是之前回收其位图的同一对象。您要么必须每次都创建一个新的可绘制对象,要么不回收实例
  • 谢谢你hoomi..这是我2天以来唯一能找到的合理答案,..你拯救了我的一天兄弟
  • 没问题。我应该将其作为答案以便您接受吗?

标签: android animationdrawable


【解决方案1】:

问题在于当您在位图上调用Bitmap.recycle() 时,您无法重用它。

当您调用setBackgroundResources(R.drawable.sensor_animation) 时,您指的是之前回收其位图的同一对象。

作为一种解决方案,您要么必须每次都创建一个新的可绘制对象,要么不回收该实例。

如果您担心内存使用情况,请尝试使用较小的位图。为不同的屏幕密度使用正确的尺寸也会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多