如何正确地将图像检索到 Android 项目的 res/drawable/ 文件夹中?

How correctly retrieve an image into the res/drawable/ folder of an Android project?

我完全是 Android 开发新手,我遇到了以下问题。

我在 res[=25] 的 drawable 目录中有一张名为 colosseum_icon.png 的图像=] 文件夹,我必须将它检索到我的 Java 代码中。所以我尝试以这种方式使用 R class:

Image image = R.drawable.colosseum_icon;

但它给了我一个错误,因为它似乎以这种方式 return 一个 int 值(也许是这个资源的标识符?或者什么?)

我错过了什么?如何将以前的图像检索到我的 Java 代码中?

你可以这样做:

Drawable drawable = getResources().getDrawable(R.drawable.colosseum_icon);

首先,您需要一个 Context(即 ActivityService)来检索应用中嵌入的图片等资源。

如果您正在尝试从 activity class 中获取 Image(抽象 class)或 Bitmap 对象:

Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.colosseum_icon);

如果您是 Android 开发人员的新手,请查看有关上下文的内容:

你必须使用 context

您可以通过使用将其作为位图获取。

Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
                                               R.drawable.colosseum_icon);

试试这个:

1) 找到您的 ImageView 字段:

ImageView imageView = (ImageView)findViewById(R.id.your_image_field_id);

2) 将 png 图标 设置为该字段:

imageView.setImageResource(R.drawable.your_icon_name);

我想这会对你有所帮助。