我想访问一个资源,如字符串或Drawable通过它的名字,而不是它的int id。
我该用哪种方法呢?
我想访问一个资源,如字符串或Drawable通过它的名字,而不是它的int id。
我该用哪种方法呢?
当前回答
如果我没理解错的话,这就是你想要的
int drawableResourceId = this.getResources().getIdentifier("nameOfDrawable", "drawable", this.getPackageName());
这里的“this”是一个活动,写出来只是为了澄清。
如果你想要strings.xml中的String或者UI元素的标识符,请替换为"drawable"
int resourceId = this.getResources().getIdentifier("nameOfResource", "id", this.getPackageName());
我警告您,这种获取标识符的方法非常缓慢,仅在需要时使用。
官方文档链接:参考资料。getIdentifier(字符串名称,字符串defType,字符串defPackage)
其他回答
int resourceID =
this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName());
我建议您使用我的方法来获取资源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;
}
如果我没理解错的话,这就是你想要的
int drawableResourceId = this.getResources().getIdentifier("nameOfDrawable", "drawable", this.getPackageName());
这里的“this”是一个活动,写出来只是为了澄清。
如果你想要strings.xml中的String或者UI元素的标识符,请替换为"drawable"
int resourceId = this.getResources().getIdentifier("nameOfResource", "id", this.getPackageName());
我警告您,这种获取标识符的方法非常缓慢,仅在需要时使用。
官方文档链接:参考资料。getIdentifier(字符串名称,字符串defType,字符串defPackage)
// image from res/drawable
int resID = getResources().getIdentifier("my_image",
"drawable", getPackageName());
// view
int resID = getResources().getIdentifier("my_resource",
"id", getPackageName());
// string
int resID = getResources().getIdentifier("my_string",
"string", getPackageName());
如果你需要在compose中这样做,你可以这样做:
val context = LocalContext.current
val drawableId = remember(iconName) {
//this block will re-calculate each time iconName has changed
val resId by derivedStateOf {
context.resources.getIdentifier(
iconName,
"drawable",
context.packageName
)
}
if (resId != 0) resId else R.drawable.some_fallback_icon //it doesn't throw an error instead resId becomes 0, so we need to check if 0 aka couldn't find the drawable.
}
//然后使用drawableId
like painterResource(id = drawableId)