unbindDrawables at PagerAdapter Android Lollipop don't work

纵饮孤独 提交于 2019-12-12 02:40:01

问题


I am trying to make Double View Pager and I override destroyItem function from my PagerAdapter just like in code bellow:

 @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();
    }
}

Everything is OK on Android KitKat, Jelly Bean, even on Gingerbread and Ice Cream Sandwich, but when I try to test my app on API 21 and higher, I have Out of memory exception. When I debug my code, I can't see the problem. Can anyone help me ? Thanks.


回答1:


I cannot see from the code that the imageview is removed from the view hierarchy, if the unbindDrawables is called on the imageView and not the viewgroup then it wont work to remove the imageview bitmap leak. I had a similar problem with out of memory that turned out to be the ImageView which prevented GC of byte[] from bitmap, and the only solution I found was to remove the ImageView from view hierarchy (and throw away the reference). It was NOT enough for me to do the following cleanup

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

I also had lots of issues with Android Studio memory analyzer which this question is focused around.

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



来源:https://stackoverflow.com/questions/33497315/unbinddrawables-at-pageradapter-android-lollipop-dont-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!