How to assign text size in sp value using java cod

2019-01-12 15:34发布

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 anyone know how to assign it in sp?

11条回答
Explosion°爆炸
2楼-- · 2019-01-12 15:51

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

view.setTextSize(TypedValue.COMPLEX_UNIT_PX, 24);
查看更多
We Are One
3楼-- · 2019-01-12 15:52

In case if anyone is looking for Kotlin way, you can do

view.textSize = 12f
查看更多
仙女界的扛把子
4楼-- · 2019-01-12 15:55

When the accepted answer doesn't work (for example when dealing with Paint) you can use:

float spTextSize = 12;
float textSize = spTextSize * getResources().getDisplayMetrics().scaledDensity;
textPaint.setTextSize(textSize);
查看更多
叛逆
5楼-- · 2019-01-12 16:00

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; 
查看更多
闹够了就滚
6楼-- · 2019-01-12 16:00

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.

查看更多
唯我独甜
7楼-- · 2019-01-12 16:04
登录 后发表回答