Convert String containing an ID into an Integer-ID

后端 未结 6 1575
别那么骄傲
别那么骄傲 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: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());
    }
    

提交回复
热议问题