Android Unbind Drawables

ezgif-3-b274179453
If you create Drawable objects on the fly you may have the unpleasant surprise that you introduced some memory leaks in your code. In that case, maybe you should unbind your drawables.

This happens because when you display a Drawable object in your Activity, that Drawable instance will be bound (via some callbacks) to your Activity and it may prevent your Drawable/Activity to be collected by the garbage collector. While the Android dudes say they fixed this issue via WeakReferences I think it’s just safer to unbind the drawables when they are not needed anymore and help the VM a little bit. Yea.. some purist say you should not help the VM but from my experience working on Swing real time trading application I learned to ignore purists and value practice and experience more 🤠. Helping the VM sometimes pays off  and in this case you can speed up the memory cleanup process. So here is my little Kotlin routine I use for this purpose:

fun AppCompatActivity.unbindDrawables(view: View?) {
    if (view == null) return

    if (view.background != null) {
        view.background.callback = null
    }
    if (view is ImageView) {
        val imageButton = view
        if (imageButton.drawable != null) {
            imageButton.drawable.callback = null
        }
    }

    if (view is ViewGroup && view !is AdapterView) {
        for (i in 0..view.childCount - 1) {
            unbindDrawables(view.getChildAt(i))
        }
        view.removeAllViews()
    }
}

And usage example:

override fun onDestroy() {
  super.onDestroy()
  unbindDrawables(findViewById(R.id.activity_main))
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s