LoginSignup
1

More than 5 years have passed since last update.

リフレクションを使って文字列からリソースIDを取得する

Posted at

一般的に、変数や文字列からリソースIDを取得したい場合、以下のように書くと思います。

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

参考ページ

Rクラスの内部クラスidのフィールドがリソースIDなので、リフレクションを使って以下のように書くこともできます。

try {
    Field field = R.id.class.getField("text_view");
    TextView textView = (TextView)findViewById(field.getInt(null));
} catch (NoSuchFieldException e) {
    e.getStackTrace();
} catch (IllegalAccessException e) {
    e.getStackTrace();
}

使いどころは皆無ですね。

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
1