我的资源文件中有很多字符串数组,我想根据用户输入以编程方式访问它们。
int c = Getter.getCurrentNumber();
String[] info = getResources().getStringArray(R.array.n_<c>);
因此,如果 c==12,则 info 应该是名称为“n_12”的字符串数组。有没有办法做到这一点,并避免在数百个案例中执行 switch 语句?
谢谢
我的资源文件中有很多字符串数组,我想根据用户输入以编程方式访问它们。
int c = Getter.getCurrentNumber();
String[] info = getResources().getStringArray(R.array.n_<c>);
因此,如果 c==12,则 info 应该是名称为“n_12”的字符串数组。有没有办法做到这一点,并避免在数百个案例中执行 switch 语句?
谢谢
如果您想按名称(以编程方式)获取资源并且不确定如何按名称寻址资源(但您知道如何通过 R 访问它),您可以这样做:
Log.d("", context.getResources().getResourceName(R.id.whichYouAlreadyKnow) );
(注意:R.id.whichYouAlreadyKnow 可以是 R.string.* R.drawable.* 等等...)
现在你知道确切的资源地址名称了
int id = getResources().getIdentifier(resource_name_that_printed_above, null, null);
干杯
您可以像这样获取资源 ID
int c = Getter.getCurrentNumber(); String resource = "n_" + c; int id = getResources().getIdentifier(resource, "array", "com.your.project");
然后只需使用该 ID
看看这里的另一个例子
getResources().getIdentifier()
。