When should the dimens.xml file be used in Android?

后端 未结 3 1098
旧巷少年郎
旧巷少年郎 2020-12-13 20:14

For instance, in a specific layout I have the following XML:



        
3条回答
  •  既然无缘
    2020-12-13 20:54

    Supplemental answer

    @Devunwired lists 3 reasons to use dimens.xml. Here are the details of how to do that.

    1. Reuse

    If you set some dp or sp value in dimens.xml once like this

    
    
        16dp
        30sp
    
    

    you can reuse it throughout your app in multiple locations.

    
    
    
    

    Then when you need to make a change, you only need to do it in one place.

    Notes

    • This is basically the same effect as using a style or theme.
    • Be careful not to give two different views the same dimen value if they really shouldn't be. If you need to make changes to one set of views but not another, then you will have to go back to each one individually, which defeats the purpose.

    2. Size Difference

    • @Devunwired called this Density difference, but if you are using dp (density independent pixels), this already takes care are the density difference problem for all but the most minor cases. So in my opinion, screen size is a more important factor for using dimens.xml.

    An 8dp padding might look great on a phone, but when the app is run on a tablet, it looks too narrow. You can solve this problem by making two (or more) different versions of dimens.xml.

    Right click your res folder and choose New > Value resource file. Then write in dimens and choose Smallest Screen Width. Write in 600 for the width (7” tablet). (There are other ways of choosing the sizes. See the documentation and this answer for more.)

    This will make another values folder that will be used for devices whose smallest screen width is 600dp. In the Android view the two dimens.xml files look like this.

    Now you can modify them independently.

    values/dimens.xml

    
    
        16dp
    
    

    values-sw600dp/dimens.xml

    
    
        64dp
    
    

    When using your dimen you only have to set it with the name you used in both dimens.xml files.

    
    
    
    

    The system will automatically choose the right value for you depending on the device the user is using.

    3. Reading in from code

    Sometimes it is a pain scaling programmatically between px and dp (see this answer for how).

    If you have a fixed dp value already defined in dimens.xml like this

    
    
        16dp
    
    

    Then you can easily get it with

    int sizeInPixels = getResources().getDimensionPixelSize(R.dimen.my_dp_value);
    

    and it will already be converted to pixels for whatever density device the user has.

提交回复
热议问题