1

我的“res”文件夹中有一个自定义文件夹、文件和自定义 XML 资源类。

我创建了一些自定义对象,我称之为:

<area id="@+id/someId" name="Some Name" />

我可以通过 R.id.someId 静态访问它们。

但是,我需要在运行时获取资源 ID,并且需要通过“名称”来执行此操作。换句话说,我在列表中显示“某个名称”,并且我需要获取知道用户从 ListView 中选择了“某个名称”的 id。(我不是在寻找 ListItem 的 id,我实际上是想搜索我的资源并获取区域 xml 对象的 id)

例如:

我想做以下事情:

int id = getIdFromResourceName("Some Name"); 

这可能吗?

我试过使用:

int i = this.getResources().getIdentifier("Some Name", "area", this.getPackageName());

...但这似乎不起作用。我总是得到0。

编辑

正如 Geobits 下面建议的那样,有没有办法从 res 文件中加载所有资源并将它们保存在数组/地图中,Map<id,name>以便我以后可以搜索它们?

感谢您的帮助!

4

3 回答 3

2

我不确定这是否是您需要的。但这是我的解决方案建议。如果您的资源是可绘制的,我会这样做:

    public int findResourceIdByName(String name) {
        Field[] fields = R.drawable.class.getFields();  // get all drawables
        try {
            for(int i=0; i<fields.length; i++) {        // loop through all drawable resources in R.drawable
                int curResId = fields[i].getInt(R.drawable.class); // Returns the value of the field in the specified object as an int.
                                                                  //This reproduces the effect of object.fieldName

                Drawable drawable = getResources().getDrawable(R.drawable.icon); // get the Drawable object
                if(drawable.getName().equals(name)) {   //getName() is NOT possible for drawable, this is just an example
                    return curResId;                    // return the corresponding resourceId
                                                        // or you could return the drawable object instead, 
                                                        // depending on what you need.
                }
            }

            return -1; // no ResourceId found for this name

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

这是使用反射,所以它不是最有效的方法。如果你经常调用这个方法,你可能需要缓存

Field[] fields = R.drawable.class.getFields();

至少。

于 2012-10-08T02:22:16.553 回答
1

试试这个:

int i = this.getResources().getIdentifier("someId", "id", this.getPackageName());

它想要的defType是它是什么形式的标识符。既然是R.id.someId,你要id。如果是R.drawable.someDrawable,你会使用drawable.

于 2012-10-08T01:35:44.860 回答
0

尝试使用,

int resID=getResources().getIdentifier("name", "id", getPackageName());  

获取资源的 ID。

于 2012-10-08T01:34:34.143 回答