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

前端 未结 2 734
悲&欢浪女
悲&欢浪女 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:42

    Though this might work OK most of the times, this is definitely not advisable. The R class is generated automatically thus you have no control over it and it could change. There is a solution to this problem using a typed array in resources. Check for example this answer.

    0 讨论(0)
  • 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).

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