如何从 android 包中的资源 id 获取 Drawable 对象?

新手上路,请多包涵

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

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

 mContext.getResources().getDrawable(drawableId)

原文由 Blaskovicz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 847
2 个回答
Drawable d = getResources().getDrawable(android.R.drawable.ic_dialog_email);
ImageView image = (ImageView)findViewById(R.id.image);
image.setImageDrawable(d);

原文由 Pete Houston 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

原文由 Sanjayrajsinh 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题