How to set a custom font in a TextView in Kotlin Android
How to set a custom font in a TextView in Kotlin Android.
Here is a step-by-step tutorial on how to set a custom font in a TextView in Kotlin Android:
Start by placing your custom font file in the
res/fontdirectory of your Android project. If thefontdirectory doesn't exist, you can create it manually.Open the XML layout file where you have the TextView that you want to apply the custom font to.
Add the
android:fontFamilyattribute to the TextView element and set its value to the path of your custom font file. For example, if your font file is named "custom_font.ttf", the attribute value should be"@font/custom_font". Here's an example:<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/custom_font"
android:text="Hello, World!" />In your Kotlin code, find the TextView using its ID and assign it to a variable. For example:
val textView = findViewById<TextView>(R.id.textView)Next, you need to create a Typeface object using your custom font file. You can do this by calling the
Typeface.createFromAsset()method and passing in theassetsobject and the path to your font file. Here's an example:val customFont = Typeface.createFromAsset(assets, "font/custom_font.ttf")Note: Make sure to adjust the file path and name to match your actual font file.
Finally, set the custom font for the TextView by calling the
setTypeface()method and passing in the Typeface object. Here's an example:textView.typeface = customFont
That's it! Your TextView will now use the custom font you specified. Repeat these steps for any other TextViews where you want to apply the custom font.
Here's the complete code example:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/custom_font"
android:text="Hello, World!" />
</layout>
val textView = findViewById<TextView>(R.id.textView)
val customFont = Typeface.createFromAsset(assets, "font/custom_font.ttf")
textView.typeface = customFont
Remember to adjust the file path and font file name according to your project's setup.