Help us understand the problem. What is going on with this article?

文字列からリソースIDを取得する

More than 5 years have passed since last update.

随分前にブログに書いたのですが、アクセスが多かったのでこちらにも書きます。
http://t-kashima.hateblo.jp/entry/20110203/1296748262

ここでは色々な方法でリソースIDを取得する方法を説明します。

文字列からリソースIDを取得する

R.string.text が直接指定できず、文字列を利用してリソースIDを取得します。

int strId = getResources().getIdentifier("text", "string", getPackageName());

同じように R.id.text_view のリソースIDを取得したい場合は以下のようにします。

int viewId = getResources().getIdentifier("text_view", "id", getPackageName());

そしてこれらを組み合わせると、TextViewを取得して文字列を設定することができます。

Resources res = getResources();
int strId = res.getIdentifier("text", "string", getPackageName());
int viewId = res.getIdentifier("text_view", "id", getPackageName());
TextView textView = (TextView)findViewById(viewId);
textView.setText(res.getString(strId));

変数と文字列からリソースIDを取得する

このやり方が便利なのは文字列とfor文の変数を使ってリソースIDを取得する場合です。

int strId, viewId;
String resViewName, resStrName;
TextView textView;
Resources res = getResources();
for(int i = 0; i < MAX; i++){
    resStrName = "str" + i;
    strId = res.getIdentifier(resStrName, "string", getPackageName());
    resViewName = "text_view" + i;
    viewId = res.getIdentifier(resViewName, "id", getPackageName());
    textView = (TextView)findViewById(viewId);
    textView.setText(res.getString(strId));
}

こうすることで動的に文字列やビューを取得することができます。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away