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)
This question is related to
android
resources
drawable
android-context
Following a solution for Kotlin programmers (from API 22)
val res = context?.let { ContextCompat.getDrawable(it, R.id.any_resource }
So now you need to use
ResourcesCompat.getDrawable(context.getResources(), R.drawable.img_user, null)
object ResourceUtils {
fun getColor(context: Context, color: Int): Int {
return ResourcesCompat.getColor(context.getResources(), color, null)
}
fun getDrawable(context: Context, drawable: Int): Drawable? {
return ResourcesCompat.getDrawable(context.getResources(), drawable, null)
}
}
use this method like :
Drawable img=ResourceUtils.getDrawable(context, R.drawable.img_user)
image.setImageDrawable(img);
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)
best way is
button.setBackgroundResource(android.R.drawable.ic_delete);
OR this for Drawable left and something like that for right etc.
int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);
and
getResources().getDrawable()
is now deprecated
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);
}
Source: Stackoverflow.com