如何检索 Android 资源 ID 及其对应的字符串?
Android:从字符串中检索资源 ID
问题
您需要将资源 ID 传递给方法,但您还想访问对应的字符串资源。例如,您有 R.drawable.icon,并且您需要整数 ID 和字符串“icon”。
解决方案
使用 Resources.getIdentifier()
一种解决方案是使用 Resources 类中的 getIdentifier() 方法。此方法将字符串资源名称和资源类型(例如,可绘制)作为参数,并返回关联的整数 ID。
// Get the integer ID for the icon int id = resources.getIdentifier("icon", "drawable", getPackageName()); // Retrieve the string resource String stringResource = resources.getString(id);
使用反射
另一个选项就是利用反射直接访问资源ID字段。请注意,此解决方案可能无法在启用代码/资源压缩的发布版本中工作。
// Get the R.drawable class Class<?> clazz = R.drawable.class; // Get the field for the icon resource Field idField = clazz.getDeclaredField("icon"); // Get the integer ID int id = idField.getInt(null); // Retrieve the string resource String stringResource = resources.getString(id);
组合两种方法
为了获得最大的灵活性,您可以组合这两种方法。将字符串资源名称传递给方法,并在方法中使用首选技术(反射或 getIdentifier())来检索 ID 和字符串。
// Method that accepts the string resource name public void processResource(String resourceName) { // Get the R.drawable class Class<?> clazz = R.drawable.class; try { // Try using reflection to get the ID Field idField = clazz.getDeclaredField(resourceName); int id = idField.getInt(null); // Retrieve the string resource String stringResource = resources.getString(id); } catch (Exception e) { // Fallback to using getIdentifier() int id = resources.getIdentifier(resourceName, "drawable", getPackageName()); String stringResource = resources.getString(id); } // Use the ID and string as needed in your method ... }
以上是如何检索 Android 资源 ID 及其对应的字符串?的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

公司安全软件导致部分应用无法正常运行的排查与解决方法许多公司为了保障内部网络安全,会部署安全软件。...

系统对接中的字段映射处理在进行系统对接时,常常会遇到一个棘手的问题:如何将A系统的接口字段有效地映�...

在使用MyBatis-Plus或其他ORM框架进行数据库操作时,经常需要根据实体类的属性名构造查询条件。如果每次都手动...

将姓名转换为数字以实现排序的解决方案在许多应用场景中,用户可能需要在群组中进行排序,尤其是在一个用...

在使用IntelliJIDEAUltimate版本启动Spring...

Java对象与数组的转换:深入探讨强制类型转换的风险与正确方法很多Java初学者会遇到将一个对象转换成数组的�...

电商平台SKU和SPU表设计详解本文将探讨电商平台中SKU和SPU的数据库设计问题,特别是如何处理用户自定义销售属...

在使用TKMyBatis进行数据库查询时,如何优雅地获取实体类变量名以构建查询条件,是一个常见的难题。本文将针...
