以编程方式访问资源名称

时间:2011-08-09 16:53:27

标签: java android

我的资源文件中有很多字符串数组,我想根据用户输入以编程方式访问它们。

int c = Getter.getCurrentNumber();
String[] info = getResources().getStringArray(R.array.n_<c>);

因此,如果c == 12,info应该是名为“n_12”的字符串数组。 有没有办法做到这一点,并避免用数百个案例做一个switch语句?

由于

2 个答案:

答案 0 :(得分:16)

您可以像这样获得资源ID

int c = Getter.getCurrentNumber();
String resource = "n_" + c;
int id = getResources().getIdentifier(resource, "array", "com.your.project");

然后只使用那个id

String[] info = getResources().getStringArray(id);

getResources().getIdentifier()上查看另一个示例here

答案 1 :(得分:3)

如果您希望按名称(以编程方式)获取资源,并且您不确定如何按名称寻址资源(但您确实知道如何通过R访问它),则可以执行以下操作:

  • 首先打印确切的资源名称,如下所示:

Log.d("", context.getResources().getResourceName(R.id.whichYouAlreadyKnow) );

(注意:R.id.whichYouAlreadyKnow可以是R.string。* R.drawable。* etc ......)
现在您知道了确切的资源地址名称

  • 取出打印的名称并按原样使用,如下所示:

int id = getResources().getIdentifier(resource_name_that_printed_above, null, null);

干杯