如何从Android包中的资源ID获取Drawable对象?

180

我需要获取一个Drawable对象以显示在图像按钮上。是否有一种方法可以使用类似下面的代码(或类似的代码)从android.R.drawable.*包中获取一个对象?

例如,如果drawableId是android.R.drawable.ic_delete

mContext.getResources().getDrawable(drawableId)
6个回答

247
Drawable d = getResources().getDrawable(android.R.drawable.ic_dialog_email);
ImageView image = (ImageView)findViewById(R.id.image);
image.setImageDrawable(d);

我还发现使用应用程序上下文似乎很有效,谢谢。 - Blaskovicz
26
从API 22开始,getDrawable(int id)方法已被弃用。请改用getDrawable(int id, Resources.Theme theme)方法。可以使用getTheme()方法进行帮助。 - Isaac Zais
1
我有一个小疑问。在这段代码中,“类型资源的getDrawable(int)方法已过时”。根据一个SO答案:
  1. 在Java中使用已弃用的方法或类是错误的吗?
从“已弃用”的定义来看:“被注释为@Deprecated的程序元素是程序员不建议使用的,通常是因为它很危险,或者因为存在更好的替代方案。”那么这个方法的更好替代方案是什么呢?
- Shubham AgaRwal

119
自从API 21版本开始,你应该使用getDrawable(int, Theme)方法替代getDrawable(int)方法,因为它允许你获取与给定屏幕密度/主题相关联的特定资源IDdrawable对象。调用已过时的getDrawable(int)方法等效于调用getDrawable(int, null)
你应该使用支持库中的以下代码:
ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)

使用这种方法等同于调用:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    return resources.getDrawable(id, context.getTheme());
} else {
    return resources.getDrawable(id);
}

context.getDrawable(id); seems to be equivalent to resources.getDrawable(id, context.getTheme()); - ErickBergmann
如果您有支持库,这可以在一行中完成: ResourcesCompat.getDrawable(resources, id, context.getTheme()); - k2col

15

自API 21起,您也可以使用:

   ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);

使用 ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email) 代替。


4
请您能否提供更详细的解释,以便我们做出选择。 - Nyandika

8

从API 21开始,`getDrawable(int id)`已被弃用

现在您需要使用

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

使用方法如下:

Drawable img=ResourceUtils.getDrawable(context, R.drawable.img_user)
image.setImageDrawable(img);

5
最好的方式是:
 button.setBackgroundResource(android.R.drawable.ic_delete);

或者使用以下代码设置Drawable left,top,right,bottom。在这种情况下,我正在设置drawable left。

int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);

并且

getResources().getDrawable()现在已经被弃用


3

针对Kotlin程序员的解决方案(使用API 22及以上版本)

val res = context?.let { ContextCompat.getDrawable(it, R.id.any_resource }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接