4

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

What is the preferred choice then?

Mikey
  • 4,218
  • 3
  • 25
  • 25

3 Answers3

10

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

MrJre
  • 7,082
  • 7
  • 53
  • 66
  • I have this .setImageDrawable(getResources().getDrawable(pickerListView.isItemChecked(position) ? R.drawable.bgpickerselected : 0)); -- this one is not working the setImageResource does – Mikey Jun 27 '12 at 09:25
  • edited the answer to reflect on why your code doesn't work ;) – MrJre Jun 27 '12 at 09:45
  • cool thanks. i need to conserve memory , project is running too many images – Mikey Jun 27 '12 at 10:16
  • i guess when you have your images on the res/ then use setImageResource instead of setImageDrawable – Mikey Jun 28 '12 at 09:24
4

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.

Andro Selva
  • 53,910
  • 52
  • 193
  • 240
0

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

jiduvah
  • 5,108
  • 6
  • 39
  • 55