Releasing a bitmap attached to an ImageView

六月ゝ 毕业季﹏ 提交于 2019-12-11 10:52:29

问题


I have a basic activity (SherlockActivity subclass), and the view it loads has a single, max-sized ImageView.

<LinearLayout xmlns:p1="http://schemas.android.com/apk/res/android"
    p1:orientation="vertical"
    p1:minWidth="25px"
    p1:minHeight="25px"
    p1:layout_width="fill_parent"
    p1:layout_height="fill_parent"
    p1:id="@+id/linearLayout1">
    <ImageView
        p1:src="@android:drawable/ic_menu_gallery"
        p1:layout_width="fill_parent"
        p1:layout_height="fill_parent"
        p1:id="@+id/imageView"
        p1:scaleType="fitCenter" />
</LinearLayout>

The only thing the Activity does is load a Bitmap and assign it to the ImageView

var iv = FindViewById<ImageView>(Resource.Id.imageView);
iv.SetBitmapImage(BitmapFactory.decodeFile(file....))

Before I worked out how to resize bitmaps on load ( http://developer.android.com/training/displaying-bitmaps/load-bitmap.html ) this was chewing up 5MB of memory each time I loaded the activity, until the app crashed (now it doesn't, but I think this problem is still there). Even if I did it like this:

  • In parent activity, tap button to open child
  • In child (the above image view) tap back
  • In parent, open child
  • In child, tap back
  • etc etc. until it crashes (about 4 times around, as it's 5MB each time!)

SO THE ACTUAL QUESTION: Am I expected to dispose of the image when the Activity stops or is destroyed? I thought in Java - or C# - things are GC'ed, so I don't need to do it. Am I missing something in the Activity lifecycle?

Both answer authors eventually came up with the right answer (the GC does it, but you can force it with recycle(). So marking correct the one which had it in the answer, so it's easier to find for others


回答1:


Try calling recycle() on the bitmap.

http://developer.android.com/reference/android/graphics/Bitmap.html#recycle%28%29




回答2:


Loading large bitmaps can cause OutOfMemoryError. You can scale down the image before loading it in your app; that will consume less memory. You may look here: https://stackoverflow.com/a/13011614/1117338



来源:https://stackoverflow.com/questions/13027209/releasing-a-bitmap-attached-to-an-imageview

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