2

intentでやりとりする情報からR.idを取るに当たって下記の様にHashMapで "news" => R.id.menu_new といった関連付けを行っているのですが、もっとスマートな方法はあるのでしょうか?
R.idをそのまま投げるやり方もあるのですが、外部とやり取りする際に文字列にするので結局変換が必要です。

static HashMap<String,Integer> menuIdTable = new HashMap<String, Integer>() {
    {
        put("news", R.id.menu_news);
        put("message", R.id.menu_message);
        put("bookmark", R.id.menu_bookmark);
        put("ranking", R.id.menu_ranking);
    }
};

1 件の回答 1

2

Resources.getIdentifier() が用意されています。

以下のような形:

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

ユーティリティメソッドと使い方は以下のようになるでしょう:

static int string2Rid( Context cx, String strId) {

    return cx.getResources().getIdentifier( strId, "id", cx.getPackageName());

}

...
// Inside Activity
{
    final String receivedIdStr = "bookmark";

    ...

    final String menuIdStr = "menu_" + receivedIdStr;
    final int menuId = string2Rid(this, menuIdStr);
    if ( menuId == 0) throw DeathByDragonError(); 

    TextView targetView = (TextView)findViewById(menuId);

    ...
}

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。