set text size programmatically android kotlin

To set the text size programmatically in Android using Kotlin, you can follow these steps:

  1. Get a reference to the TextView: First, you need to obtain a reference to the TextView whose text size you want to set. You can do this by using the findViewById method in your activity or fragment.

  2. Set the text size: Once you have the reference to the TextView, you can use the setTextSize method to set the desired text size. The setTextSize method takes two parameters: the first parameter is the unit of the text size, and the second parameter is the actual size of the text.

  3. The unit of the text size can be specified using the constants defined in the TypedValue class, such as TypedValue.COMPLEX_UNIT_SP for scaled pixels, TypedValue.COMPLEX_UNIT_DIP for density-independent pixels, or TypedValue.COMPLEX_UNIT_PX for pixels.

  4. The size of the text can be specified as a float value representing the desired size in the specified unit.

  5. Apply the changes: Finally, you need to apply the changes to the TextView by calling the invalidate method to redraw the TextView with the updated text size.

Here's an example of how you can set the text size programmatically in Kotlin:

val textView = findViewById<TextView>(R.id.textView)
val textSize = 18f // desired text size in scaled pixels

textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize)
textView.invalidate()

In this example, we first obtain a reference to the TextView with the id textView. Then, we set the text size to 18 scaled pixels using the setTextSize method. Finally, we call the invalidate method to apply the changes and redraw the TextView.

Remember to replace R.id.textView with the actual id of your TextView in your layout file.