How to assign text size in sp value using java code

后端 未结 11 1930
無奈伤痛
無奈伤痛 2020-12-04 05:14

If I assign an integer value to change a certain text size of a TextView using java code, the value is interpreted as pixel (px).

Now does

相关标签:
11条回答
  • 2020-12-04 06:06

    http://developer.android.com/reference/android/widget/TextView.html#setTextSize%28int,%20float%29

    Example:

    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 65);
    
    0 讨论(0)
  • 2020-12-04 06:06

    This is code for the convert PX to SP format. 100% Works

    view.setTextSize(TypedValue.COMPLEX_UNIT_PX, 24);
    
    0 讨论(0)
  • 2020-12-04 06:08

    Cleaner and more reusable approach is

    define text size in dimens.xml file inside res/values/ directory:

    </resources>
       <dimen name="text_medium">14sp</dimen>
    </resources>
    

    and then apply it to the TextView:

    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimension(R.dimen.text_medium));
    
    0 讨论(0)
  • 2020-12-04 06:12

    By default setTextSize, without units work in SP (scales pixel)

    public void setTextSize (float size) 
    Added in API level 1
    Set the default text size to the given value, interpreted as "scaled pixel" units. This 
    size is adjusted based on the current density and user font size preference.
    
    0 讨论(0)
  • 2020-12-04 06:15

    You can use a DisplayMetrics object to help convert between pixels and scaled pixels with the scaledDensity attribute.

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    pixelSize = (int)scaledPixelSize * dm.scaledDensity; 
    
    0 讨论(0)
提交回复
热议问题