Load dimension value from res/values/dimension.xml from source code

前端 未结 9 1788
情书的邮戳
情书的邮戳 2020-11-27 09:30

I\'d like to load the value as it is. I have two dimension.xml files, one in /res/values/dimension.xml and the other one in /res/values-sw360

9条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 09:57

    In my dimens.xml I have

    48dp
    

    In code If I do

    int valueInPixels = (int) getResources().getDimension(R.dimen.test)
    

    this will return 72 which as docs state is multiplied by density of current phone (48dp x 1.5 in my case)

    exactly as docs state :

    Retrieve a dimensional for a particular resource ID. Unit conversions are based on the current DisplayMetrics associated with the resources.

    so if you want exact dp value just as in xml just divide it with DisplayMetrics density

    int dp = (int) (getResources().getDimension(R.dimen.test) / getResources().getDisplayMetrics().density)
    

    dp will be 48 now

提交回复
热议问题