Reputation: 6160
I need to get a Drawable object to display on an image button. Is there a way to use the code below (or something like it) to get an object from the android.R.drawable.* package?
for example if drawableId was android.R.drawable.ic_delete
mContext.getResources().getDrawable(drawableId)
Upvotes: 180
Views: 188051
Reputation: 6758
The best way is
button.setBackgroundResource(android.R.drawable.ic_delete);
OR use the below code for Drawable left, top, right, bottom. I'm setting drawable left in this case.
int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);
and
getResources().getDrawable()
is now deprecated
Upvotes: 5
Reputation: 17138
So now you need to use
ResourcesCompat.getDrawable(context.getResources(), R.drawable.img_user, null)
import android.content.Context
import android.graphics.drawable.Drawable
import androidx.core.content.res.ResourcesCompat
object ResourceUtils {
fun getColor(context: Context, color: Int): Int {
return ResourcesCompat.getColor(context.resources, color, null)
}
fun getDrawable(context: Context, drawable: Int): Drawable? {
return ResourcesCompat.getDrawable(context.resources, drawable, null)
}
}
use this method like :
Drawable img=ResourceUtils.getDrawable(context, R.drawable.img_user)
image.setImageDrawable(img);
Upvotes: 9
Reputation: 940
Following a solution for Kotlin programmers (from API 22)
val res = context?.let { ContextCompat.getDrawable(it, R.id.any_resource }
Upvotes: 3
Reputation: 23796
As of API 21, you should use the getDrawable(int, Theme)
method instead of getDrawable(int)
, as it allows you to fetch a drawable
object associated with a particular resource ID
for the given screen density/theme
. Calling the deprecated
getDrawable(int)
method is equivalent to calling getDrawable(int, null)
.
You should use the following code from the support library instead:
ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)
Using this method is equivalent to calling:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return resources.getDrawable(id, context.getTheme());
} else {
return resources.getDrawable(id);
}
Upvotes: 119
Reputation: 2372
As of API 21, you could also use:
ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);
Instead of ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)
Upvotes: 15
Reputation: 15089
Drawable d = getResources().getDrawable(android.R.drawable.ic_dialog_email);
ImageView image = (ImageView)findViewById(R.id.image);
image.setImageDrawable(d);
Upvotes: 248