Android 以编程方式设置 textSize
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20364993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting textSize programmatically
提问by Rakeeb Rajbhandari
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, getResources().getDimension(R.dimen.result_font));
The following code works, but the R.dimen.result_font
is taken as a much bigger value than it really is. Its maybe about 18sp-22sp or 24sp according to the screen size ... But the size set here is at least about 50sp. Can someone please recommend something ?
下面的代码有效,但R.dimen.result_font
被认为是比实际值大得多的值。根据屏幕大小,它可能大约为 18sp-22sp 或 24sp……但这里设置的大小至少约为 50sp。有人可以推荐一些东西吗?
回答by Glenn
You have to change it to TypedValue.COMPLEX_UNIT_PX
because getDimension(id)
returns a dimen value from resources and implicitlyconverted to px.
您必须将其更改为TypedValue.COMPLEX_UNIT_PX
因为getDimension(id)
从资源返回一个 dimen 值并隐式转换为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))
回答by Jayakrishnan PM
Requirement
要求
Suppose we want to set textView Size programmatically from a resource file.
假设我们想从资源文件中以编程方式设置 textView 大小。
Dimension resource file(res/values/dimens.xml)
维度资源文件(res/values/dimens.xml)
<resources>
<dimen name="result_font">16sp</dimen>
</resources>
Solution
解决方案
First get dimenvalue from resource file into a variable "textSizeInSp".
首先从资源文件中获取维度值到变量“textSizeInSp”中。
int textSizeInSp = (int) getResources().getDimension(R.dimen.result_font);
Next convert 16sp value into equal pixels.
接下来将16sp 值转换为相等的像素。
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,
让我们设置 TextSize,
textView.setTextSize(convertSpToPixels(textSizeInSp , getApplicationContext()));
All together,
全部一起,
int textSizeInSp = (int) getResources().getDimension(R.dimen.result_font);
textView.setTextSize(convertSpToPixels(textSizeInSp , getApplicationContext()));