在我的情况下如何使用动态名称访问资源? [英] How to access resource with dynamic name in my case?

查看:20
本文介绍了在我的情况下如何使用动态名称访问资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I get the image name as a variable like following:

var imageName = SERVICE.getImg();

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

Then, how can I get the resource with R.drawable.????, I tried R.drawable[imageName], but it failed. Any suggestions?

推荐答案

int id = getResources().getIdentifier(imageName, type, package);

这将为您获取您正在寻找的资源的 ID. 有了它,您就可以从 R 类访问资源.

This will get you the ID of the resource you are looking for. With it, you can then access the resource from the R class.

仅使用 name 参数:

Using only the name parameter:

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

You can also include all the 3 info in the "name" parameter using the following format: "package:type/image_name", something like:

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

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

This is useful when you're working with external components or libraries that you can't, or don't want to, change how getIdentifier() is called. e.g.: AOSP Launcher3

这篇关于在我的情况下如何使用动态名称访问资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆