Consequences of drawable.setCallback(null);

前端 未结 1 1969
感情败类
感情败类 2020-12-14 09:31

While trying to implement small in-memory cache of Drawables, I learned that to avoid memory leaks after closing activity I need to unbind those Drawables: set their callbac

1条回答
  •  有刺的猬
    2020-12-14 10:07

    You should not cache Drawables -- the Drawable object is very stateful, and intended to be used by one and only one owner.

    If you want to implement a cache, you should be caching the drawable's constant state.

    The constant state is retrieve with this:

    http://developer.android.com/reference/android/graphics/drawable/Drawable.html#getConstantState()

    (Note this method can return null; not all Drawables have constant state.)

    You can later instantiate new Drawables from a constant state with this:

    http://developer.android.com/reference/android/graphics/drawable/Drawable.ConstantState.html#newDrawable(android.content.res.Resources)

    Also keep in mind that Resources already maintains a cache of Drawables for you, using this facility, so there is no need for you to implement your own cache for any Drawables you are retrieving from Resources.

    And if you are making your own Drawables outside of resources, I would strongly recommend making a cache of the underlying data (such as a bitmap downloaded from the network) then trying to mess with the constant state. (And again, definitely don't cache Drawable objects themselves.)

    0 讨论(0)
提交回复
热议问题