以编程方式设置textSize

Rak*_*ari 55 android

textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, getResources().getDimension(R.dimen.result_font));
Run Code Online (Sandbox Code Playgroud)

下面的代码可以工作,但是R.dimen.result_font它被视为比实际更大的值.根据屏幕尺寸,它可能约为18sp-22sp或24sp ......但这里设置的尺寸至少约为50sp.有人可以推荐一下吗?

Gle*_*enn 162

您必须将其更改为,TypedValue.COMPLEX_UNIT_PX因为getDimension(id)从资源返回维度值并隐式转换为px.

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 
           getResources().getDimension(R.dimen.result_font));
Run Code Online (Sandbox Code Playgroud)


Jay*_* PM 10

需求

假设我们想要从资源文件中以编程方式设置textView Size.

维度资源文件(res/values/dimens.xml)

<resources>     
   <dimen name="result_font">16sp</dimen>
</resources>
Run Code Online (Sandbox Code Playgroud)

首先从资源文件获取dimen值到变量"textSizeInSp".

int textSizeInSp = (int) getResources().getDimension(R.dimen.result_font);
Run Code Online (Sandbox Code Playgroud)

接下来将16 sp值转换为相等的像素.

为此创建一个方法.

 public static float convertSpToPixels(float sp, Context context) {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, context.getResources().getDisplayMetrics());
}
Run Code Online (Sandbox Code Playgroud)

我们设置TextSize,

textView.setTextSize(convertSpToPixels(textSizeInSp , getApplicationContext()));
Run Code Online (Sandbox Code Playgroud)

全部一起,

int textSizeInSp = (int) getResources().getDimension(R.dimen.result_font);
textView.setTextSize(convertSpToPixels(textSizeInSp , getApplicationContext()));
Run Code Online (Sandbox Code Playgroud)