如果我使用java代码分配一个整数值来改变TextView的某个文本大小,该值将被解释为像素(px)。

有人知道如何在sp中赋值吗?


当前回答

根据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()));
}

我构建了这个函数来计算任何维度的像素:

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

这里的单位是TypedValue.COMPLEX_UNIT_SP。

其他回答

你可以使用DisplayMetrics对象通过scaledDensity属性在像素和缩放像素之间进行转换。

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
pixelSize = (int)scaledPixelSize * dm.scaledDensity; 
semeTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 
                       context.getResources().getDimension(R.dimen.text_size_in_dp))

默认设置为setTextSize,不使用SP单位(像素比例)

public void setTextSize (float size)

在API级别1中添加 将默认文本大小设置为给定值,解释为“缩放像素”单位。这 大小根据当前密度和用户字体大小首选项进行调整。

根据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()));
}

我构建了这个函数来计算任何维度的像素:

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

这里的单位是TypedValue.COMPLEX_UNIT_SP。

这是转换PX到SP格式的代码。 100%的工作

view.setTextSize(TypedValue.COMPLEX_UNIT_PX, 24);