【问题标题】:How to access resource with dynamic name in my case?在我的情况下如何使用动态名称访问资源?
【发布时间】:2011-09-28 20:33:27
【问题描述】:

如果我将图像名称作为变量获取,如下所示:

var imageName = SERVICE.getImg();

那我怎么获取R.drawable.????的资源,我试过R.drawable[imageName],但是失败了。有什么建议吗?

【问题讨论】:

标签: android android-layout android-emulator android-widget android-ndk


【解决方案1】:
int id = getResources().getIdentifier(imageName, type, package);

This will get you the ID of the resource you are looking for. 有了它,你就可以从 R 类中访问资源了。

仅使用name 参数:

您还可以使用以下格式在“名称”参数中包含所有 3 个信息:"package:type/image_name",类似于:

int id = getResources().getIdentifier("com.my.app:drawable/my_image", null, null);

当您使用无法或不想更改getIdentifier() 调用方式的外部组件或库时,这很有用。例如:AOSP Launcher3

【讨论】:

  • @nicholas,我得到了资源未找到异常。如果我在“drawable”文件夹中有一个名为“icon1.gif”的图像,它不是 getIdentifier("icon1", "gif", "drawable") 吗??
  • 你看链接了吗?我认为它会是 ("icon1", "drawable", "the. contains.package")
  • @nicholas,.contain.package 是什么意思???不是包含 package = "projectName/res/drawable" 吗??
  • @Leem:这个包就是你的项目包。
  • 确保在 imageName 字符串中保留扩展名(.png 或 .jpg),否则 resourceId 将设置为 0x0 整数,表示 没有此类资源找到了
【解决方案2】:

试试这个:

int id = getResources().getIdentifier(imageName, "drawable", getPackageName());

【讨论】:

  • 至于R.id.???等价的,就是int id = getResources().getIdentifier(imageName, "id", getPackageName());
  • 这是有代价的,如果你尝试Refactor -> Remove un-used resources,它会删除你动态访问的资源。因此,除非绝对必要,否则最好不要这样做。
  • 可以确认这对我有用,虽然我的代码是int resourceId = context.getResources().getIdentifier(layoutName, "layout", context.getPackageName());
  • 完美答案.. 谢谢!
【解决方案3】:

你需要反思。

假设您有 R.drawable.image1,如果您想通过字符串名称“image1”访问它,以下应该可以:

String Name = "image1";
int id = R.drawable.class.getField(Name).getInt(null);

但请注意,它只获取图像的 Id,您仍然需要充气器才能从中获取实际的可绘制对象。

【讨论】:

  • 当其他getIdentifier() 方法失败时,为什么这会起作用?
【解决方案4】:

使用此功能

public static String getResourceString(String name, Context context) {
    int nameResourceID = context.getResources().getIdentifier(name,
            "string", context.getApplicationInfo().packageName);
    if (nameResourceID == 0) {
        throw new IllegalArgumentException(
                "No resource string found with name " + name);
    } else {
        return context.getString(nameResourceID);
    }
}

【讨论】:

    【解决方案5】:

    您可以使用getIdentifier 方法,它会通过名称为您提供资源ID。查看this线程了解更多详情。

    【讨论】:

    • getIdentifier() 中的参数“defPackage”是什么???不是“projectName/res/drawable”吗??
    • defPackage - 如果名称中不包含“package:”,则要查找的可选默认包。可以为 null 以要求显式包。您的名称应该类似于 org.anddev.android.testproject:drawable/bug 其中 bug 是可绘制名称,而 org.anddev.android.testproject 是您的主包名称。请阅读文章!!
    猜你喜欢
    • 2011-06-29
    • 2012-08-21
    • 2021-11-01
    • 2011-07-31
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多