7

私のアプリでは、105 などの結果コードを返す Web リクエストを実行しています。そのような文字列リソースがあります。

<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 は、XML ファイルにも含まれるドローアブル フォルダー内のリソース ImageView の名前です。「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 に答える