198

String や Drawable などのリソースに、int ID ではなく名前でアクセスしたい。

これにはどの方法を使用しますか?

4

10 に答える 10

363

私の理解が正しければ、これはあなたが望むものです

int drawableResourceId = this.getResources().getIdentifier("nameOfDrawable", "drawable", this.getPackageName());

「これ」はアクティビティであり、明確にするために書かれています。

strings.xml の文字列または UI 要素の識別子が必要な場合は、"drawable" に置き換えます。

int resourceId = this.getResources().getIdentifier("nameOfResource", "id", this.getPackageName());

警告しますが、識別子を取得するこの方法は非常に時間がかかります。必要な場合にのみ使用してください。

公式ドキュメントへのリンク: Resources.getIdentifier(String name, String defType, String defPackage)

于 2010-08-13T11:46:28.350 に答える
158

次のようになります。

R.drawable.resourcename

Android.REclipseを混乱させる可能性があるため、名前空間をインポートしていないことを確認してください(使用している場合)。

それがうまくいかない場合は、いつでもコンテキストのgetResourcesメソッドを使用できます...

Drawable resImg = this.context.getResources().getDrawable(R.drawable.resource);

、またはその他のサブクラスthis.contextとして初期化されます。ActivityServiceContext

アップデート:

必要な名前の場合、Resourcesクラス(によって返されるgetResources())にはgetResourceName(int)メソッドとgetResourceTypeName(int)?があります。

アップデート2

Resourcesクラスには次のメソッドがあります。

public int getIdentifier (String name, String defType, String defPackage) 

これは、指定されたリソース名、タイプ、およびパッケージの整数を返します。

于 2010-08-13T11:42:58.303 に答える
25
int resourceID = 
    this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName());
于 2012-05-14T09:34:58.120 に答える
22

Kotlin Version経由Extension Function

名前でリソース ID を検索するには Kotlin で、kotlin ファイルに以下のスニペットを追加します。

ExtensionFunctions.kt

import android.content.Context
import android.content.res.Resources

fun Context.resIdByName(resIdName: String?, resType: String): Int {
    resIdName?.let {
        return resources.getIdentifier(it, resType, packageName)
    }
    throw Resources.NotFoundException()
}

Usage

resIdByNameメソッドを使用してコンテキスト参照があれば、すべてのリソース ID にアクセスできるようになりました。

val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
val stringResId = context.resIdByName("title_home", "string")
.
.
.    
于 2018-09-29T13:11:59.587 に答える
6

私の方法を使用してリソース ID を取得することをお勧めします。遅い getIdentidier() メソッドを使用するよりもはるかに効率的です。

コードは次のとおりです。

/**
 * @author Lonkly
 * @param variableName - name of drawable, e.g R.drawable.<b>image</b>
 * @param с - class of resource, e.g R.drawable.class or R.raw.class
 * @return integer id of resource
 */
public static int getResId(String variableName, Class<?> с) {

    Field field = null;
    int resId = 0;
    try {
        field = с.getField(variableName);
        try {
            resId = field.getInt(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return resId;

}
于 2011-08-29T08:29:48.543 に答える
3

Kotlinでは、次のことがうまくいきます:

val id = resources.getIdentifier("your_resource_name", "drawable", context?.getPackageName())

リソースがmipmapフォルダーに配置されている場合、「drawable」の代わりにパラメーター「mipmap」を使用できます。

于 2020-06-06T09:49:07.570 に答える
0

このクラスは、リソースを処理するのに非常に役立つことがわかりました。次のように、寸法、色、ドローアブル、および文字列を処理するための定義済みのメソッドがいくつかあります。

public static String getString(Context context, String stringId) {
    int sid = getStringId(context, stringId);
    if (sid > 0) {
        return context.getResources().getString(sid);
    } else {
        return "";
    }
}
于 2016-06-30T15:27:15.713 に答える
0

@lonkly ソリューションに加えて

  1. 反射とフィールドのアクセシビリティを参照してください
  2. 不要な変数

方法:

/**
 * lookup a resource id by field name in static R.class 
 * 
 * @author - ceph3us
 * @param variableName - name of drawable, e.g R.drawable.<b>image</b>
 * @param с            - class of resource, e.g R.drawable.class or R.raw.class
 * @return integer id of resource
 */
public static int getResId(String variableName, Class<?> с)
                     throws android.content.res.Resources.NotFoundException {
    try {
        // lookup field in class 
        java.lang.reflect.Field field = с.getField(variableName);
        // always set access when using reflections  
        // preventing IllegalAccessException   
        field.setAccessible(true);
        // we can use here also Field.get() and do a cast 
        // receiver reference is null as it's static field 
        return field.getInt(null);
    } catch (Exception e) {
        // rethrow as not found ex
        throw new Resources.NotFoundException(e.getMessage());
    }
}
于 2017-06-27T15:15:39.827 に答える