【问题标题】:unbindDrawables at PagerAdapter Android Lollipop don't workPagerAdapter Android Lollipop 上的 unbindDrawables 不起作用
【发布时间】:2023-03-11 01:18:01
【问题描述】:

我正在尝试制作 Double View Pager,并从我的 PagerAdapter 覆盖 destroyItem 函数,就像在下面的代码中一样:

 @Override
public void destroyItem(ViewGroup container, int position, Object object)
{
    container.removeView((View) object);
    unbindDrawables((View) object);
    System.gc();
    object = null;
}

protected void unbindDrawables(View view)
{
    if (view instanceof ImageView)
    {
        Drawable drawable = ((ImageView) view).getDrawable();
        if (drawable instanceof BitmapDrawable) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            Bitmap bitmap = bitmapDrawable.getBitmap();
            bitmap.recycle();
        }
        ImageWorker.cancelWork(((ImageView) view));
        ((ImageView) view).setImageResource(0);
        ((ImageView) view).setImageDrawable(null);
    }
    if (view.getBackground() != null)
    {
        view.getBackground().setCallback(null);
    }
    if (view instanceof ViewGroup)
    {
        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++)
        {
            unbindDrawables(((ViewGroup) view).getChildAt(i));
        }
        if (!(view instanceof AdapterView<?>))
        {
            ((ViewGroup) view).removeAllViews();
        }
        //((ViewGroup) view).removeAllViews();
    }
}

在 Android KitKat、Jelly Bean,甚至在 Gingerbread 和 Ice Cream Sandwich 上一切正常,但是当我尝试在 API 21 及更高版本上测试我的应用程序时,出现内存不足异常。当我调试我的代码时,我看不到问题所在。谁能帮我 ?谢谢。

【问题讨论】:

    标签: android android-viewpager android-5.0-lollipop


    【解决方案1】:

    我无法从代码中看到 imageview 已从视图层次结构中删除,如果在 imageView 而不是 viewgroup 上调用 unbindDrawables,则无法删除 imageview 位图泄漏。我遇到了类似的内存不足问题,结果证明是 ImageView 阻止了位图中的 byte[] GC,我找到的唯一解决方案是从视图层次结构中删除 ImageView(并丢弃引用)。我做以下清理是不够的

        if (imageView.getBackground() != null) {
            imageView.getBackground().setCallback(null);
        }
        setImageBackground(imageView, null);
        imageView.setImageBitmap(null);
        imageView.setImageDrawable(null);
    

    我在 Android Studio 内存分析器上也遇到了很多问题,这个问题就是围绕着这个问题展开的。

    Leaked unreferenced byte[] originally from bitmap but recycled() causing memory-leak (until activity stopped)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-19
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-25
      • 2014-12-29
      相关资源
      最近更新 更多