Android: Accessing string.xml using variable name

后端 未结 2 590
借酒劲吻你
借酒劲吻你 2020-12-28 21:20

I want to display a message to the user depending upon a prompt I receive from another part of the program. There can be a number of prompts & they are stored in an enum

2条回答
  •  春和景丽
    2020-12-28 21:58

    See Resources.getIdentifier: http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29 . You can try something like this:

    public void showPrompt(Prompt prompt, String label) {
        String message = (String) getResources().getText(getResources().getIdentifier(label, "string", null));
        //show a dialog box with message
    }
    

    Try that out and see what that does for you.

    EDIT: meh. Try this instead.

    public void showPrompt(Prompt prompt, String label) {
        String message = (String) getResources().getText(getResources().getIdentifier(label, "string", ""));
        //show a dialog box with message
    }
    

    Turns out you have to specify the your package identifier (so if your AndroidManifest.xml has com.blah.blah.blah as the Package put that in the third parameter.

提交回复
热议问题