以编程方式设置 textSize

textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, getResources().getDimension(R.dimen.result_font));

下面的代码可以工作,但是 R.dimen.result_font被认为是一个比实际大得多的值。根据屏幕大小,大概是18-22或者24勺... ... 但是这里设置的大小至少是50勺。有人能给我推荐点什么吗?

53459 次浏览

You have to change it to TypedValue.COMPLEX_UNIT_PX because getDimension(id) returns a dimen value from resources and implicitly converted to px.

Java:

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getResources().getDimension(R.dimen.result_font));

Kotlin:

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
resources.getDimension(R.dimen.result_font))

Requirement

Suppose we want to set textView Size programmatically from a resource file.

Dimension resource file (res/values/dimens.xml)

<resources>
<dimen name="result_font">16sp</dimen>
</resources>

Solution

First get dimen value from resource file into a variable "textSizeInSp".

int textSizeInSp = (int) getResources().getDimension(R.dimen.result_font);

Next convert 16 sp value into equal pixels.

for that create a method.

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

Let's set TextSize,

textView.setTextSize(convertSpToPixels(textSizeInSp , getApplicationContext()));

All together,

int textSizeInSp = (int) getResources().getDimension(R.dimen.result_font);
textView.setTextSize(convertSpToPixels(textSizeInSp , getApplicationContext()));