Is it a good thing to write logic based on the hex value of id generated in R.java android

前端 未结 2 756
悲&欢浪女
悲&欢浪女 2021-01-29 08:17

This what I have seen in an android application. They have a number of image buttons with ids

R.java :
        public static final int img1=0x7f090080;
        p         


        
2条回答
  •  耶瑟儿~
    2021-01-29 08:49

    You might want to use reflection.

    Add this method to your code:

    protected final static int getResourceID
    (final String resName, final String resType, final Context ctx)
    {
        final int ResourceID =
            ctx.getResources().getIdentifier(resName, resType,
                ctx.getApplicationInfo().packageName);
        if (ResourceID == 0)
        {
            throw new IllegalArgumentException
            (
                "No resource string found with name " + resName
            );
        }
        else
        {
            return ResourceID;
        }
    }
    

    And use it like this:

    int myID =
        getResourceID("your_resource_name", "drawable", getApplicationContext());
    

    Note: no path (and no extension, in case of images).

提交回复
热议问题