7

在我的应用程序中,我做了一个返回一些结果代码的 Web 请求,例如 105。我有看起来像这样的字符串资源

<string name="r105">O.K.</string>
<string name="r106">Something went wrong.</string>
<string name="r333">Fatal error.</string>

现在我想做这样的事情

Toast.makeText(parent.getApplicationContext(),
        parent.getString(R.string.r+resultCode), Toast.LENGTH_LONG).show();

whiler+resultCode是资源标识符。

这不起作用。知道怎么做吗?

4

4 回答 4

16

以一种简单的方式试试这个getResources().getIdentifier(name, defType, defPackage)

Toast.makeText(this, getResources().getIdentifier("r"+resultcode, "string", 
getPackageName()), Toast.LENGTH_LONG).show();
于 2011-12-29T13:32:35.953 回答
4

您可以使用getResources().getIdentifier(name, defType, defPackage). 像这样的东西:

// Assuming resultCode is an int, use %s for String
int id = getResources().getIdentifier(String.format("r%d", resultCode), 
                                      "string", getPackageName());
String result = getString(id);
于 2011-12-29T13:18:35.393 回答
-1

尝试如下,它对我有用。为你使用parent.getApplicationContext()

String str = getString(R.string.r)+resultCode;

        Toast.makeText(getApplicationContext(),
                str, Toast.LENGTH_LONG).show();
于 2011-12-29T13:02:14.710 回答
-1

从字符串中获取资源 ID 的简单方法。这里resourceName是可绘制文件夹中资源ImageView的名称,它也包含在XML文件中。我得到“id”你可以使用“string”。

int resID = getResources().getIdentifier(resourceName, "id", getPackageName());
ImageView im = (ImageView) findViewById(resID);
Context context = im.getContext();
int id = context.getResources().getIdentifier(resourceName, "drawable",
context.getPackageName());
im.setImageResource(id);
于 2015-04-27T18:04:43.837 回答