How to assign text size in sp value using java code

后端 未结 11 2043
無奈伤痛
無奈伤痛 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 05:48

    Based on the the source code of setTextSize:

    public void setTextSize(int unit, float size) {
        Context c = getContext();
        Resources r;
    
        if (c == null)
            r = Resources.getSystem();
        else
            r = c.getResources();
    
        setRawTextSize(TypedValue.applyDimension(
            unit, size, r.getDisplayMetrics()));
    }
    

    I build this function for calulating any demension to pixels:

    int getPixels(int unit, float size) {
        DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
        return (int)TypedValue.applyDimension(unit, size, metrics);
    }
    

    Where unit is something like TypedValue.COMPLEX_UNIT_SP.

提交回复
热议问题