简体   繁体   中英

What is textview.setTextSize()?

In my android game, there is a textview. I am setting the text size using following code.

textview.setTextSize(30);

30 is in pixels. 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.

To manage font size, you should use "sp". eg : textview.setTextSize(20sp). "sp" is scale-independat pixel and is encouraged by android documentaion to be used for managing text on different screen sizes.

More information on how sp is calculated, can be found here.

@Rasoul Miri's answer works well for Java because Java does type promotion for numbers.

Kotlin, on the other hand won't lift a finger and would just pedantically nag you with:

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.

So, @Rasoul's example becomes.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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