Add Custom Font in kotlin

πŸ›  Step 1: Put the Font in Your Project

  1. In Android Studio, go to: app/src/main/res/
  2. Create a new folder named font (if it doesn’t already exist).
    • Right-click res β†’ New β†’ Android Resource Directory
    • Select font as the resource type β†’ OK.
  3. Copy your .ttf or .otf font file into the res/font/ folder.
    Example: poppins_regular.ttf

πŸ›  Step 2: Reference the Font in XML (optional)

You can directly use it in XML layouts:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello Custom Font!"
    android:fontFamily="@font/poppins_regular"
    android:textSize="20sp"
    android:textColor="@android:color/black"/>

πŸ›  Step 3: Apply Custom Font in Kotlin Code

If you want to apply it programmatically:

import android.graphics.Typeface
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.TextView

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val textView = findViewById<TextView>(R.id.myTextView)

        // Load font from res/font folder
        val typeface: Typeface = resources.getFont(R.font.poppins_regular)
        textView.typeface = typeface
    }
}

πŸ›  Step 4: Apply Globally (Optional)

If you want the custom font everywhere in your app, do it with a Theme in styles.xml:

<!-- In res/values/themes.xml -->
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    <item name="android:fontFamily">@font/poppins_regular</item>
</style>

Then apply this theme to your AndroidManifest.xml:

<application
    android:theme="@style/AppTheme">

See Complete Tutorial

Leave a Comment

Your email address will not be published. Required fields are marked *