Difference of setting an Image from Resource to Drawables?

android

Solution

According to the documentation `setImageResource` does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. So your question would be better if you'd ask in which cases `setImageResource` is a better choice above `setImageDrawable`.

My guess would be that the `setImageResource` is used for lazy loading images, and `setImageDrawable` is used when you already loaded the image through a Drawable during view initiation. Which one is suiting you best probably depends on whether you have more serious memory constraints or not; in my experience, `setImageResource` is scarcely ever needed.

And to answer why your code doesn't work; this is because you can't do `getDrawable()` from a resourceId 0, this throws an exception as it can't find the resource. Since `setImageResource` is lazy loading, it checks if the resource is 0 before creating the Drawable, and hence throws no exception. You could probably refactor it to an `if(checked) setImageDrawable(..) else setImageDrawable(null);`

Problem

Example of this is for setImageResource vs. setImageDrawable same goes for a Background? What is the preferred choice then?

Original source

Related problems