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 に答える