Skip to main content

How to change the font style of a TextView in Kotlin Android

How to change the font style of a TextView in Kotlin Android.

Here's a step-by-step tutorial on how to change the font style of a TextView in Kotlin Android:

Step 1: Add a font file to your project

  • First, you need to add a font file to your project's res/font directory. If the font directory doesn't exist, create it.
  • Copy your desired font file (with the extension .ttf or .otf) into the font directory.

Step 2: Create a TextView in your layout XML file

  • Open your layout XML file (e.g., activity_main.xml) and add a TextView element.
  • Set the desired attributes for the TextView, such as android:id, android:layout_width, android:layout_height, etc.

Step 3: Set the font style programmatically

  • Open your Kotlin class file (e.g., MainActivity.kt) that corresponds to the layout file.
  • Inside the onCreate method, find the TextView using its ID using the findViewById method.
  • Declare a variable to hold the Typeface object for your custom font:
    val customFont: Typeface = Typeface.createFromAsset(assets, "font/font_name.ttf")
    Replace "font/font_name.ttf" with the path to your font file.
  • Set the typeface of the TextView to the custom font:
    textView.typeface = customFont
    Replace textView with the name of your TextView variable.

Step 4: Apply the custom font style in XML (optional)

  • If you want to set the custom font style directly in your XML layout file, you can use the android:fontFamily attribute:
    <TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/font_name"
    ... />
    Replace "@font/font_name" with the name of your font file (without the extension).

That's it! You have successfully changed the font style of a TextView in Kotlin Android. You can repeat these steps to apply custom font styles to other TextViews in your project as well.

Note: Make sure to replace font_name with the actual name of your font file in all the code examples provided.