简体   繁体   English

什么是 textview.setTextSize()?

[英]What is textview.setTextSize()?

In my android game, there is a textview. I am setting the text size using following code.在我的 android 游戏中,有一个 textview。我使用以下代码设置文本大小。

textview.setTextSize(30);

30 is in pixels. 30以像素为单位。 But what exactly it is?但它到底是什么? Is it the height or width of a character?它是字符的高度还是宽度? Is it ordinal no.是序号吗? ?

要在 android(java 或 kotlin)中设置文本大小,只需使用 SP

textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);

setTextSize(30) - It sets the font size of your text based on one pixel dimension on the device and since different devices have different pixel sizes, based on their screen size and resultion, the final font size will look so differently on devices. setTextSize(30) - 它根据设备上的一个像素尺寸设置文本的字体大小,并且由于不同的设备具有不同的像素大小,根据它们的屏幕大小和结果,最终的字体大小在设备上看起来会有很大不同。

To manage font size, you should use "sp".要管理字体大小,您应该使用“sp”。 eg : textview.setTextSize(20sp).例如:textview.setTextSize(20sp)。 "sp" is scale-independat pixel and is encouraged by android documentaion to be used for managing text on different screen sizes. “sp”是与比例无关的像素,android 文档鼓励将其用于管理不同屏幕尺寸上的文本。

More information on how sp is calculated, can be found here.可以在此处找到有关如何计算 sp 的更多信息

@Rasoul Miri's answer works well for Java because Java does type promotion for numbers. @Rasoul Miri 的答案适用于 Java,因为 Java 确实对数字进行了类型提升。

Kotlin, on the other hand won't lift a finger and would just pedantically nag you with:另一方面,Kotlin 不会动一动手指,只会迂腐地唠叨你:

The integer literal does not conform to the expected type Float

So, be sure to beg it to do explicit conversion for you with a : .toFloat() call.因此,请务必通过 : .toFloat()调用请求它为您进行显式转换。

So, @Rasoul's example becomes.所以,@Rasoul 的例子就变成了。

textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14.toFloat());

NB: Would have added this as edit to @Rasoul's answer but StackOverflow says The suggested Edit queue is full .注意:本可以将此作为编辑添加到@Rasoul 的答案中,但 StackOverflow 说 TheSuggested The suggested Edit queue is full

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM