Search code examples
androidbuttonkotlintextviewcustom-font

Android: Custom font works for TextView, not for Button


I cannot get a Button to use my custom font. It works fine with a TextView, not with a Button (which is a subclass of TextView).

I am using Android Studio 3.1.2 with minSdkVersion 26 and Kotlin.

res/font/font.xml

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@font/my-custom-font" />
</font-family>

res/layout/fragment.xml

...
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/myButton"
    android:maxWidth="30dp"
    android:minWidth="30dp"
    android:maxHeight="40dp"
    android:minHeight="40dp"
    android:fontFamily="@font/my-custom-font"
    android:textSize="20dp"
    android:text="a" />
...

The above works. Replace TextView with Button and it stops working.

Edit: I want to use a custom font to hold the icons for our Buttons, instead of using images and ImageButtons. We find a custom font is easier to manage than images.


Solution

  • Add a style to your button:

    Create a new style under styles.xml :

    <style name="main_button">
        <item name="android:fontFamily">@font/my-custom-font</item>
        <item name="android:background">@drawable/btn_blue</item>
        <item name="android:textColor">#FFFF</item>
        <item name="android:textAllCaps">false</item>
        <item name="android:foreground">?attr/selectableItemBackground</item>
    </style>
    

    enter whatever values you want. Make sure to include the fontFamily:

    Then on your button, add the style:

    <Button
        android:id="@+id/id"
        style="@style/main_button" />