info@androidpaper.co.in

How to change the font in Kotlin Android?

In Android app development, customizing the appearance of UI elements is essential for creating visually appealing and unique user interfaces. One common customization is changing the font of a TextView. By changing the font, you can give your app a distinct look and feel that aligns with your design vision.
We will explore how to change the font of a TextView in an Android app using Kotlin. We'll cover the necessary steps, from adding the font file to your project to programmatically applying it to TextView. Let's get started and make your app's text truly stand out!

Start by creating a new folder called assets in the src/main directory of your Android project if it doesn't already exist.
Inside the assets folder, create another folder called fonts. This is where you will place your font files (e.g., .ttf or .otf files).
Copy your desired font file into the fonts folder. For example, let's say you have a font file named custom_font.ttf that you want to use.
Open the layout XML file that contains the TextView you want to modify, or create a new one if needed.
Add a TextView element to your layout XML file:

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello, World!"
    />

In your Kotlin file (e.g., your Activity or Fragment), find the reference to the TextView using findViewById or view binding:

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

Use the Typeface class to load the custom font and set it for your TextView:

val customFont: Typeface = Typeface.createFromAsset(assets, "fonts/custom_font.ttf")
textView.typeface = customFont

Make sure to replace "fonts/custom_font.ttf" with the correct path to your font file relative to the assets folder.
Optionally, you can further customize the TextView by setting other properties such as text, size, or color:

textView.text = "Hello, Kotlin!"
textView.textSize = 18f // Set the text size in SP
textView.setTextColor(Color.BLACK) // Set the text color

That's it! When you run your application, the TextView should display the text with the custom font you specified.