A full example of custom fonts in XML using data binding and including font caching.

Related tags

Font fontbinding
Overview

[Deprecated]

Fonts in XML are now supported by the Android support library as of 26.0, including in styles and themes. I recommend using the support library and IDE integration for all your modern font needs! https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html#using-support-lib

fontbinding

Easy custom fonts in XML using data binding.

No setup required, no extra Java code, and no custom views.

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:font="@{`alegreya`}"
    />

Drawing

This example includes a simple font cache that automatically loads names from your assets/fonts folder and lazy-loads typefaces. Just drag and drop font files and use them in XML by their normal or lowercase filenames (e.g. "Roboto-Italic" or "roboto-italic" for Roboto-Italic.otf). That's it!

Data Binding

Make sure to use the data binding framework to inflate your layout.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DataBindingUtil.setContentView(this, R.layout.activity_main);
    }
}

More about data binding: http://developer.android.com/tools/data-binding/guide.html

Custom Naming

You can set custom names for your fonts, but you don't have to.

FontCache.getInstance().addFont("alegreya", "Alegreya-Regular.ttf");

Note:

It's not currently possible to define custom attributes in styles using data binding. If you require this, check out Calligraphy by Chris Jenx.

You might also like...
Custom font library for android | Library to change/add font of Entire Android Application at once without wasting your time - TextViews, EditText, Buttons, Views etc.,

AppFontChanger In a Single shot change font of Entire Android Application - TextViews, EditText, Buttons, Views etc., Kindly use the following links t

Implementation of a TextView and all its direct/indirect subclasses with native support for the Roboto fonts, includes the brand new Roboto Slab fonts.
Implementation of a TextView and all its direct/indirect subclasses with native support for the Roboto fonts, includes the brand new Roboto Slab fonts.

Android-RobotoTextView Implementation of a TextView and all its direct/indirect subclasses with native support for the Roboto fonts, includes the bran

An ActivityScenario extension and a Junit4 TestRule to simulate changing the font size on a device/emulator, as it would be done by going to Settings display Font size

FontSizeActivityScenario and FontSizeTestRule An ActivityScenario and a Junit4 TestRule to be used together with its org.junit.runners.Parameterized.

A sample project in Kotlin to demonstrate AndroidX, MVVM, Coroutines, Hilt, Room, Data Binding, View Binding, Retrofit, Moshi, Leak Canary and Repository pattern.

This repository contains a sample project in Kotlin to demonstrate AndroidX, MVVM, Coroutines, Hilt, Room, Data Binding, View Binding, Retrofit, Moshi, Leak Canary and Repository pattern

Androidicons is a professional, handcrafted icon set with 250 icons in 14 different colors and 5 sizes, including an icon font and all sources.

Android Developer Icons Android Developer Icons is a custom icon set, created by Opoloo. Included are: 250 hand-crafted, pixel-perfect icons in 5 size

A Clean Architecture App that uses clean Architecture (app, presentation, domain, data) packages to use coffee items API using MVVM Architecture, Coroutines, Retrofit2, Pagination, Live Data, Data Binding, Hilt , SOLID Principles , Navigation Component , RoomDb. This program will read from your android application string.xml file and generate translated strings.xml files in your preferred languages using google sheet.
This program will read from your android application string.xml file and generate translated strings.xml files in your preferred languages using google sheet.

Localize your application content This program will read from your application string.xml file and generate translated strings.xml files in your prefe

Custom View classes for TextView, EditText & Buttons - to set custom fonts
Custom View classes for TextView, EditText & Buttons - to set custom fonts

CustomFontView Custom font classes for TextView, EditText & Buttons How to integrate the library in your app? Gradle Dependecy dependencies {

A Full-Stack mobile app, including Android & Server, Simple-Poem 简诗. You can write poem in graceful & traditional Chinese style.
A Full-Stack mobile app, including Android & Server, Simple-Poem 简诗. You can write poem in graceful & traditional Chinese style.

JianShi 简诗 A Full-Stack mobile app, including Android side & Server side, Simple-Poem 简诗. You can write poem in graceful & traditional Chinese style.

Don't write a ViewPager Adapter! Hook up your ViewPager to your data model using Android Data Binding Framework. With Kotlin support!
Don't write a ViewPager Adapter! Hook up your ViewPager to your data model using Android Data Binding Framework. With Kotlin support!

Don't write a ViewPager Adapter! Hook up your ViewPager to your data model using Android Data Binding Framework. Show some ❤️ 💋 Sweet and short libra

KmmCaching - An application that illustrates fetching data from remote data source and caching it in local storage
KmmCaching - An application that illustrates fetching data from remote data source and caching it in local storage

An application that illustrates fetching data from remote data source and caching it in local storage for both IOS and Android platforms using Kotlin Multiplatform Mobile and SqlDelight.

Twidere-Android Twidere is a powerful twitter client for Android 1.6+ 1 , which gives you a full Holo experience and nearly full Twitter's feature.
Twidere-Android Twidere is a powerful twitter client for Android 1.6+ 1 , which gives you a full Holo experience and nearly full Twitter's feature.

Twidere for Android Material Design ready and feature rich Twitter/Mastodon/Fanfou app for Android 4.1+. Enjoy Fediverse now! Twidere-Android is maint

Use Android Data Binding wih Live Data to glue View Model and Android

Gruop-C Spliff Summary Use Android Data Binding wih Live Data to glue View Model and Android. Asynchronous communications implemented with KotlinX Cor

Useful library to use custom fonts in your android app
Useful library to use custom fonts in your android app

EasyFonts A simple and useful android library to use custom fonts in android apps without adding fonts into asset/resource folder.Also by using this l

Custom fonts in Android the easy way...
Custom fonts in Android the easy way...

This version of Calligraphy has reached its end-of-life and is no longer maintained. Please migrate to Calligraphy 3! Calligraphy Custom fonts in Andr

IconicDroid is a custom Android Drawable which allows to draw icons from several iconic fonts.
IconicDroid is a custom Android Drawable which allows to draw icons from several iconic fonts.

IconicDroid IconicDroid is a custom Android Drawable which allows to draw icons from several iconic fonts. Try out the sample application on the Googl

Android Library to use custom fonts with ease.
Android Library to use custom fonts with ease.

FontometricsLibrary A Simple Android Library to use Custom Fonts with Ease. Use Customs Fonts in your Android project without adding any .ttf/.otf in

Set custom font in Android application

MagicViews Provides a simple way to set custom font in Android application. Adding to your project Add the library as a dependency to your build.gradl

A spring-boot project that demonstrates data caching using Redis

A spring-boot project that demonstrates data caching using Redis

Comments
  • Should it work to use this method with Design Support components and custom layouts?

    Should it work to use this method with Design Support components and custom layouts?

    In my project I have both a TabLayout and a NavigationDrawer.

    For the TabLayout I inflate each tab as a custom layout. Like this:

    LinearLayout appTab = (LinearLayout) LayoutInflater.from(activity).inflate(R.layout.custom_tab, null);
    TextView appCardsTextView = (TextView) appTab.findViewById(R.id.tab_text);
    appCardsTextView.setText("Application");
    ImageView appCardsImageView = (ImageView) appTab.findViewById(R.id.tab_icon);
    appCardsImageView.setImageResource(R.drawable.ic_application);
    tabLayout.getTabAt(0).setCustomView(appTab);
    

    custom_tab.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <layout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    
        <data>
        </data>
    
        <LinearLayout
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:orientation="vertical"
            android:gravity="center_vertical|center_horizontal">
    
            <ImageView
                android:layout_width="34dp"
                android:layout_height="34dp"
                android:id="@+id/tab_icon"/>
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:id="@+id/tab_text"
                android:textColor="@color/white"
                android:textSize="@dimen/tab_label"
                android:text="testing"
                app:font="@{`lato_hairline`}" <---- NOT WORKING!
            />
    
        </LinearLayout>
    
    </layout>
    

    Is there a way to make it set the font in a situation like this through XML? I found a workaround setting it through Java that I use for now: appCardsTextView.setTypeface(FontCache.getInstance(appCardsTextView.getContext()).get("lato_hairline")); But for XML it does not bind to the BindingAdapter

    I have the same problem for my NavigationView (sidebar) where I might have to get each item and set it through Java as well.

    Thanks.

    opened by nilsi 3
  • Removing memory leak and simplifying the api

    Removing memory leak and simplifying the api

    Thank @lisawray for this great utility, I thought of these improvements and implemented them.

    • Holding on to the context is a static manner is a memory leak and we can avoid that altogether.
    • Also there is no need for instantiating this class (since our maps are static) and thus we can simplify the API by just using get() method.
    • Also we can lazily instantiate our maps.
    opened by kayvannj 2
  • Is it possible to pass the font from the styles.xml?

    Is it possible to pass the font from the styles.xml?

    I have many textview which needs common style with same font. I am curious about to know, does resources (such as style.xml, strings.xml) support the binding attributes?

    opened by urveshpatel50 1
  • Font cache checks for wrong name

    Font cache checks for wrong name

    In the font cache the font is stored in the cache with the filename, but when this font is needed for another time the containsKey checks for the alias of the font.

    Example: fontFilename: MyFont-SemiBold.otf stored in cache: fontFilename checked: filename (myfont-semibold) [which is the alias]

    opened by andras-gerendas 1
Owner
Lisa Wray
Lisa Wray
Custom fonts in Android the easy way...

This version of Calligraphy has reached its end-of-life and is no longer maintained. Please migrate to Calligraphy 3! Calligraphy Custom fonts in Andr

Christopher Jenkins 8.6k Jan 3, 2023
Android Library to use custom fonts with ease.

FontometricsLibrary A Simple Android Library to use Custom Fonts with Ease. Use Customs Fonts in your Android project without adding any .ttf/.otf in

Ishmeet Singh 188 Nov 15, 2022
Material and Holo iconic fonts.

Android Icon Fonts Material and Holo iconic fonts. Source Material Extracted 433 Material Design icons from Google's Project Polymer website by Shreya

Evgeny Shishkin 223 Dec 27, 2022
A lightweight Android library for use iconic fonts.

Print A lightweight Android library for use iconic fonts. Download Gradle: compile 'com.github.johnkil.print:print:1.3.1' Maven: <dependency> <gro

Evgeny Shishkin 202 Dec 27, 2022
A lightweight Android library for use iconic fonts.

Print A lightweight Android library for use iconic fonts. Download Gradle: compile 'com.github.johnkil.print:print:1.3.1' Maven: <dependency> <gro

Evgeny Shishkin 202 Dec 27, 2022
help you change the module font easily.(方便快速的为应用内所有组件更换字体)

FontsManager 有待重构 English Readme please cilick here 字体管理器,方便快速的为应用内所有组件更换字体。 作者微博: @GcsSloop Demo演示 如何添加 1.在Project的build.gradle中添加仓库地址 allprojects {

sloop 479 Nov 29, 2022
Fontize is an Android library that enables multi-font selection functionality to diversify your app.

Fontize Android Library Built with ❤︎ by Gourav Khunger Fontize is an Android library, written in kotlin, that enables your android app have multiple

Gourav Khunger 8 Nov 28, 2022
A library that gives full control over text related technologies such as bidirectional algorithm, open type shaping, text typesetting and text rendering

Tehreer-Android Tehreer is a library which gives full control over following text related technologies. Bidirectional Algorithm OpenType Shaping Engin

Tehreer 61 Dec 15, 2022
****. Use the native and support library variants instead - https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html. An android library that makes it easy to add custom fonts to edittexts and textviews

Add to your project Add this line to your dependencies in build.gradle compile 'in.workarounds.typography:typography:0.0.8' Using the views There are

Workarounds 43 Nov 6, 2021