我想访问一个资源,如字符串或Drawable通过它的名字,而不是它的int id。
我该用哪种方法呢?
我想访问一个资源,如字符串或Drawable通过它的名字,而不是它的int id。
我该用哪种方法呢?
当前回答
// 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());
其他回答
除了@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());
}
}
int resourceID =
this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.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)
我发现这个类在处理资源方面非常有用。它有一些定义的方法来处理尺寸,颜色,drawables和字符串,就像这个:
public static String getString(Context context, String stringId) {
int sid = getStringId(context, stringId);
if (sid > 0) {
return context.getResources().getString(sid);
} else {
return "";
}
}
// 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());