How to set text size using dimension from xml at runtime programmatically?

后端 未结 3 929
醉梦人生
醉梦人生 2020-12-12 18:05

In dimens.xml, I have:

18sp

In runtime, I get this value and set the text size of a text vi

相关标签:
3条回答
  • 2020-12-12 18:13

    Both methods getDimensionPixelSize() and getDimension() use screen density to calculate pixels. Your phone screen density is obviously hdpi (240dpi) so it uses 1.5 scale to convert dp to sp. Simple math 18 * 1.5 = 27.

    It seems that your tablet density is mdpi (160dpi) so scale is just 1:1.

    But if you compare real size of both texts it should be the same.

    The best way is just create two dimens.xml files one in values folder for phone, and another in values-sw600dp for tablets (you could use also values-sw720dp-land folder to store dimensions for 10 inch tablets in landscape orientation).

    You could read more about dimensions in Android at: http://android4beginners.com/2013/07/appendix-c-everything-about-sizes-and-dimensions-in-android/

    0 讨论(0)
  • You can use sdp (Scalable desnsity pixels) https://github.com/intuit/sdp in place of dp, this will definately save your life

    0 讨论(0)
  • 2020-12-12 18:27

    Add dimension in dimens.xml:

       <dimen name="text_medium">18sp</dimen>
    

    Set the size in code:

    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.text_medium));
    
    0 讨论(0)
提交回复
热议问题