2

I know how to use @drawable but how do I set @android:drawable/ic_image in code?

in XML, it would be

android:icon="@drawable/my_image"

or

android:icon="@mipmap/my_image"

and for android:drawable, it would be:

android:icon="@android:drawable/ic_menu_delete"

but how to do the latest in code to set an image?

And which should I use?

Cœur
  • 37,241
  • 25
  • 195
  • 267
pixel
  • 9,653
  • 16
  • 82
  • 149

3 Answers3

4

This will help you out. Don't use getResource().getDrawable(). Its deprecated.

Android getResources().getDrawable() deprecated API 22

So basically:

 Drawable drawable = ContextCompat.getDrawable(this, R.drawable.your_drawable);
    img.setBackgroundDrawable(drawable);

For android drawables you do:

ContextCompat.getDrawable(this, android.R.drawable.your_drawable);

For Mipmaps:

ContextCompat.getDrawable(this, R.mipmap.your_drawable);
Arnold Balliu
  • 1,099
  • 10
  • 21
1

You can do it like this code:

img.setImageDrawable(getResources().getDrawable(R.drawable.ic_image, null));
Fred
  • 3,365
  • 4
  • 36
  • 57
  • @ArnoldB this getDrawable(id) is deprecated. but my suggestion is getDrawable(id, theme). In my answer I send null as second parameter. – Fred Dec 30 '15 at 23:02
  • Yes. But still that does not make it correct. The way Google wants you to do it is the way I put in as an answer. That method will most likely get deprecated too as they have methods for themes with ResourcesCompat too. He asked for the correct way. – Arnold Balliu Dec 30 '15 at 23:05
  • No problem. This has been very confusing for a while since Google keeps changing it. I don't even know why they don't have it down yet... really annoying. – Arnold Balliu Dec 30 '15 at 23:13
1

to use Android resources you should use "android.R" prefix like in resource name. this is code example:

    view.setBackgroundResource(android.R.drawable.ic_menu_delete);
ant
  • 397
  • 1
  • 5
  • 19