Convert String containing an ID into an Integer-ID

后端 未结 6 1554
别那么骄傲
别那么骄傲 2020-12-10 03:57

I have a short question:

How is it possible to convert a String, containing the Id of a Drawable, which is

String idString = \"R.drawable.bubblegum\"         


        
相关标签:
6条回答
  • 2020-12-10 04:20

    if your idString is constant, i.e. it's doesn't change during runtime, follow DeeV's answer. If it changes, you can take a look at getIdentifier method.

    0 讨论(0)
  • 2020-12-10 04:21

    Although this question is rather old already, the thing you're missing is that "id" and "drawable" are different resource types. So instead of

    getResources().getIdentifier(stringId, "id", "my.Package");
    

    it's

    getResources().getIdentifier(stringId, "drawable", "my.Package");
    

    You can also get package name with the activity context like activityContext.getPackageName()

    /**
     * Returns Identifier of String into it's ID as defined in R.java file.
     * @param pContext
     * @param pString defnied in Strings.xml resource name e.g: action_item_help
     * @return
     */
    public static int getStringIdentifier(Context pContext, String pString){
        return pContext.getResources().getIdentifier(pString, "string", pContext.getPackageName());
    }
    
    0 讨论(0)
  • 2020-12-10 04:21

    You could try the following

    int id = getResources().getIdentifier("arr_name"+positionSelected,
                            "array", rootview.getContext().getPackageName());
    

    I use in spinner dropdown, get array string follow parent spinner may help you!

    0 讨论(0)
  • 2020-12-10 04:28

    int idInt = R.drawable.bubblegum;

    Unless there's something I'm missing here.

    0 讨论(0)
  • 2020-12-10 04:36

    Call getIdentifier() on the Resources object you get via getResources(), as seen in these StackOverflow questions:

    • Is possible in Android to findView by String id?
    • Android findViewbyId with a variant string
    • How to access R.string.xxx resources from a method by passing string 'xxx' as parameter to that method?
    • Dynamically build a resource Identifier
    • How to access the values from strings.xml dynamically?
    • Drawable resource using a variable

    among others.

    0 讨论(0)
  • 2020-12-10 04:37

    At least, I couldn't get a solution for this problem. It seems that there's no way to convert a String "R.id.mytext" into an integer like R.id.mytext that can be used in findViewById(R.id.myText).

    0 讨论(0)
提交回复
热议问题