LoginSignup
106
106

More than 5 years have passed since last update.

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

Last updated at Posted at 2013-01-06

随分前にブログに書いたのですが、アクセスが多かったのでこちらにも書きます。
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));
}

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

106
106
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
106
106