変数名からリソースIDを取得する

もし、R.string.kagawa を何かの理由で直接参照できない場合、
以下のようにすれば、簡単に id を取得することが出来ます。

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


以下は、R.id.kagawa_txt の id を取得して利用する方法です。

int resId = getResources().getIdentifier("kagawa_txt", "id", getPackageName());
TextView kagawa_txt = (TextView)findViewById(resId);
kagawa_txt.setText("Hello,World");


そして、これらを組み合わせると以下のようにできます。

Resources res = getResources();
int strId = getResources().getIdentifier("kagawa", "string", getPackageName());
int resId = getResources().getIdentifier("kagawa_txt", "id", getPackageName());
TextView kagawa_txt = (TextView)findViewById(resId);
kagawa_txt.setText(res.getString(strId));


以下は、べつの便利な例です。

for(int i=0;i<MAX;i++){
  String name = "kagawa"+i;
  int strId = getResources().getIdentifier(name, "string", getPackageName());
  String str = res.getString(strId);
}


これはかなり便利!いいね!


ref:

mokkouyouの開発日記 RにあるリソースIDを変数名から取得したい
Resourcesクラスを使ったリソースの参照 - リソース管理 - Android入門
追記
  • 2013年1月6日 以下にもう少し分かりやすくまとめました

http://qiita.com/items/9462af782fb5f1a2a7da