Extending ImageView causes memory leak

五迷三道 提交于 2021-01-27 20:20:16

问题


Good day

I'm extending the ImageView class because I need it to be a square, the problem is that it seems to be causing a memory leak, because if I use the not extended ImageView class there is no output in MAT. This is the extended version, as you can see is very simple:

public class SquareImageView extends ImageView {

    public SquareImageView(Context context) {
        super(context);
    }

    public SquareImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    }

}

and I'm implementing it as a GridView item, something like this:

<FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:foreground="@drawable/item_button">

    <com.gc.materialdesign.views.ProgressBarCircularIndeterminate
            android:id="@+id/progressBarCircularIndeterminate"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:layout_gravity="center"
            android:background="@color/orange"/>

    <!-- if I use <ImageView/>, everything is ok -->
    <com.example.widgets.SquareImageView
            android:id="@+id/picture"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"/>

</FrameLayout>

This is what I get in the histogram after opening and closing the fragment containing the gridview 10 times, as you can see the retained heap is huge, at this point I already forced the GC:

The list with incoming references of 1 of the 10 retained objects:

And the path to gc roots (excluding weak references):

I managed to reduce the retained heap by recycling the ImageView bitmaps:

But I can't figure out why those 10 objects are being retained. As I said in the beginning, if I use ImageView instead of the extended one, there is no leak at all. If you could give me a hint, it would be great.

来源:https://stackoverflow.com/questions/31839580/extending-imageview-causes-memory-leak

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