String や Drawable などのリソースに、int ID ではなく名前でアクセスしたい。
これにはどの方法を使用しますか?
String や Drawable などのリソースに、int ID ではなく名前でアクセスしたい。
これにはどの方法を使用しますか?
私の理解が正しければ、これはあなたが望むものです
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)
次のようになります。
R.drawable.resourcename
Android.R
Eclipseを混乱させる可能性があるため、名前空間をインポートしていないことを確認してください(使用している場合)。
それがうまくいかない場合は、いつでもコンテキストのgetResources
メソッドを使用できます...
Drawable resImg = this.context.getResources().getDrawable(R.drawable.resource);
、またはその他のサブクラスthis.context
として初期化されます。Activity
Service
Context
アップデート:
必要な名前の場合、Resources
クラス(によって返されるgetResources()
)にはgetResourceName(int)
メソッドとgetResourceTypeName(int)
?があります。
アップデート2:
Resources
クラスには次のメソッドがあります。
public int getIdentifier (String name, String defType, String defPackage)
これは、指定されたリソース名、タイプ、およびパッケージの整数を返します。
int resourceID =
this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName());
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")
.
.
.
私の方法を使用してリソース 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;
}
Kotlinでは、次のことがうまくいきます:
val id = resources.getIdentifier("your_resource_name", "drawable", context?.getPackageName())
リソースがmipmapフォルダーに配置されている場合、「drawable」の代わりにパラメーター「mipmap」を使用できます。
このクラスは、リソースを処理するのに非常に役立つことがわかりました。次のように、寸法、色、ドローアブル、および文字列を処理するための定義済みのメソッドがいくつかあります。
public static String getString(Context context, String stringId) {
int sid = getStringId(context, stringId);
if (sid > 0) {
return context.getResources().getString(sid);
} else {
return "";
}
}
@lonkly ソリューションに加えて
方法:
/**
* 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());
}
}