Friday, January 9, 2015

How to set Button font in Android

Button Typeface
The button is a highly used Android interface element. The user can tap on a Button to perform some task. This tutorial will show how we can change the Android button’s default font in the XML layout file. The button’s typeface property allows us to change the default font of the button widget. For example, we can write android:typeface=”monospace” inside the Button tag to replace the default font with a monospace font.
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8FF"
    android:padding="24dp">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btnDefault"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button - Default Font"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btnMonospace"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Button - Monospace Font"
        android:typeface="monospace"
        app:layout_constraintStart_toStartOf="@+id/btnDefault"
        app:layout_constraintTop_toBottomOf="@+id/btnDefault" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btnSans"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Button - Sans Font"
        android:typeface="sans"
        app:layout_constraintStart_toStartOf="@+id/btnMonospace"
        app:layout_constraintTop_toBottomOf="@+id/btnMonospace" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btnSerif"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Button - Serif Font"
        android:typeface="serif"
        app:layout_constraintStart_toStartOf="@+id/btnSans"
        app:layout_constraintTop_toBottomOf="@+id/btnSans" />

</androidx.constraintlayout.widget.ConstraintLayout>