Mikey
Mikey

Reputation: 4238

Difference of setting an Image from Resource to Drawables?

Example of this is for setImageResource vs. setImageDrawable same goes for a Background?

What is the preferred choice then?

Upvotes: 4

Views: 2744

Answers (3)

MrJre
MrJre

Reputation: 7161

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);

Upvotes: 10

jiduvah
jiduvah

Reputation: 5168

A drawable would be in memory setImageResource is a point to the id stored in gen files

Upvotes: 0

Andro Selva
Andro Selva

Reputation: 54322

Actually there is a bit difference in both the methods.

the first one, setImageResource is used when you have the required image in your res folder. But whereas the second method setImageDrawable is likely to be used when you create a Object of type Drawable.

Also it should be noted that, a resource file can be converted to a Drawable type but it is not possible to convert Drawable to Resource.

When you have your image in your res folder, it is well and good if you use the first method instead of converting it to Drawable and then using the second method.

Upvotes: 4

Related Questions