Skip to main content

How to set different text styles (bold, italic, underline) in a TextView in Kotlin Android

How to set different text styles (bold, italic, underline) in a TextView in Kotlin Android.

Here is a step-by-step tutorial on how to set different text styles (bold, italic, underline) in a TextView in Kotlin for Android:

Step 1: Create a new Android project in Android Studio and open the layout file (usually named activity_main.xml) for the desired activity.

Step 2: Add a TextView element to the layout file. You can customize its attributes like text size, color, and alignment as per your requirements. For example:

<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="16sp"
android:textColor="#000000"
android:textAlignment="center" />

Step 3: In the corresponding Kotlin file (usually named MainActivity.kt), define a variable for the TextView and initialize it using the findViewById method in the onCreate method. For example:

val myTextView: TextView = findViewById(R.id.myTextView)

Step 4: To set the text as bold, use the setTypeface method with the Typeface.BOLD constant. For example:

myTextView.setTypeface(null, Typeface.BOLD)

Step 5: To set the text as italic, use the setTypeface method with the Typeface.ITALIC constant. For example:

myTextView.setTypeface(null, Typeface.ITALIC)

Step 6: To set the text as underlined, use the setPaintFlags method with the Paint.UNDERLINE_TEXT_FLAG constant. For example:

myTextView.paintFlags = myTextView.paintFlags or Paint.UNDERLINE_TEXT_FLAG

Step 7: To set a combination of styles, you can combine the constants using the or operator. For example, to set both bold and italic styles:

myTextView.setTypeface(null, Typeface.BOLD_ITALIC)

Step 8: Build and run your application to see the changes in the TextView's text style.

That's it! You have successfully set different text styles (bold, italic, underline) in a TextView using Kotlin for Android. You can apply these styles dynamically based on your application's logic and user interactions.

Note: Remember to import the necessary classes at the top of your Kotlin file:

import android.graphics.Paint
import android.graphics.Typeface
import android.widget.TextView

Feel free to explore more customization options and attributes available for TextViews in the Android documentation.