pixel
pixel

Reputation: 10547

Android - set an image using @android:drawable/AnImage programmatically

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?

Upvotes: 2

Views: 265

Answers (3)

Arnold Balliu
Arnold Balliu

Reputation: 1119

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

Upvotes: 4

ant
ant

Reputation: 407

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

Upvotes: 1

Fred
Fred

Reputation: 3421

You can do it like this code:

img.setImageDrawable(getResources().getDrawable(R.drawable.ic_image, null));

Upvotes: 1

Related Questions