780

So I'd like to change the android:fontFamily in Android but I don't see any pre-defined fonts in Android. How do I select one of the pre-defined ones? I don't really need to define my own TypeFace but all I need is something different from what it shows right now.

<TextView
    android:id="@+id/HeaderText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="52dp"
    android:gravity="center"
    android:text="CallerBlocker"
    android:textSize="40dp"
    android:fontFamily="Arial"
 />

It seems what I did up there won't really work! BTW android:fontFamily="Arial" was a stupid attempt!

Piyush
  • 1,622
  • 1
  • 12
  • 28
Tarik
  • 73,061
  • 78
  • 222
  • 327
  • check out this link https://stackoverflow.com/questions/2376250/custom-fonts-and-xml-layouts-android/48642116#48642116 – duggu Feb 06 '18 at 11:47

37 Answers37

1704

From android 4.1 / 4.2 / 5.0, the following Roboto font families are available:

android:fontFamily="sans-serif"           // roboto regular
android:fontFamily="sans-serif-light"     // roboto light
android:fontFamily="sans-serif-condensed" // roboto condensed
android:fontFamily="sans-serif-black"     // roboto black
android:fontFamily="sans-serif-thin"      // roboto thin (android 4.2)
android:fontFamily="sans-serif-medium"    // roboto medium (android 5.0)

enter image description here

in combination with

android:textStyle="normal|bold|italic"

this 16 variants are possible:

  • Roboto regular
  • Roboto italic
  • Roboto bold
  • Roboto bold italic
  • Roboto-Light
  • Roboto-Light italic
  • Roboto-Thin
  • Roboto-Thin italic
  • Roboto-Condensed
  • Roboto-Condensed italic
  • Roboto-Condensed bold
  • Roboto-Condensed bold italic
  • Roboto-Black
  • Roboto-Black italic
  • Roboto-Medium
  • Roboto-Medium italic

fonts.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="font_family_light">sans-serif-light</string>
    <string name="font_family_medium">sans-serif-medium</string>
    <string name="font_family_regular">sans-serif</string>
    <string name="font_family_condensed">sans-serif-condensed</string>
    <string name="font_family_black">sans-serif-black</string>
    <string name="font_family_thin">sans-serif-thin</string>
</resources>
Tadas Valaitis
  • 870
  • 10
  • 11
Jakob Eriksson
  • 17,996
  • 1
  • 21
  • 32
  • 18
    Don't forget this: android:fontFamily="sans-serif-thin" // roboto thin – Sam Lu Feb 12 '13 at 09:15
  • 6
    I saw a variant called "black small caps" in the [roboto specimen book](http://commondatastorage.googleapis.com/androiddevelopers/design/Roboto_Specimen_Book_20111129.pdf), but I don't manage to use it. Using `android:fontFamily="sans-serif-black-small-caps"` doesnt work. Does someone know? – tbruyelle May 29 '13 at 13:44
  • 3
    i am not able to find any of these font-family what have you typed here .i am not able to find "sans-serif" together. – Monty Aug 16 '13 at 04:10
  • 9
    This is a nice list. Does anyone have a link to where this information comes from? It would be nice if Google had this in their documentation in an easy to find place, say for the documentation of `android:fontFamily` on TextView. – Christopher Perry Oct 30 '13 at 17:53
  • 2
    Any clue of what's the source of this answer's information? I'd like to read further about it – Christian García Dec 03 '13 at 10:55
  • 3
    This would be great information for, oh I don't know, how about **the `TextView` API Javadocs**. Just sayin'. Apparently [this is the only official reference](http://developer.android.com/about/versions/android-4.1.html). – Adam Mackler Feb 21 '14 at 23:54
  • Is it accurate to say that ``fontFamily`` supercedes ``typeface``? Are we now no longer able to use serif or monospace? I don't think ``typeface`` is formally deprecated, just ignored when ``fontFamily`` is also present. – Rad Haring Mar 06 '14 at 15:03
  • I have updated this answer with details of where the source of this information comes from and how to get a definitive list of `android:fontFamily` values, even vendor ones, from your devices. Its just waiting on peer review. – Simon Apr 09 '14 at 10:12
  • 8
    The definitive list of fonts can be found in [system_fonts.xml](https://android.googlesource.com/platform/frameworks/base/+/master/data/fonts/system_fonts.xml) as explained [here](http://stackoverflow.com/a/24072492/598094) – Newtonx Jun 06 '14 at 01:17
  • Just a quick quesrtion, if I use android:fontFamily in versions prior to (< 4.1) Jelly Bean, will it crash my app or just be ignored? – Sandra Sep 03 '14 at 14:55
  • 1
    @Sandra it will be ignored, so it's safe to use – Jakob Eriksson Sep 04 '14 at 12:42
  • 1
    Where can I find in the documentation about the available font-families ? – android developer Nov 05 '14 at 15:16
  • "sans-serif" (roboto regular) is the default, right? – android developer Jan 22 '15 at 08:45
  • How can I use roboto condensed light? Thanks – Ricardo Feb 08 '15 at 21:48
  • 2
    @Ricardo Best way is to look at the source: https://android.googlesource.com/platform/frameworks/base/+/lollipop-release/data/fonts/system_fonts.xml and https://android.googlesource.com/platform/frameworks/base/+/master/data/fonts/fonts.xml , which means you want to use "sans-serif-condensed-light" – android developer Apr 23 '15 at 21:41
  • 1
    What if you use sans-serif-thin on Android 4.1? Will it default to sans-serif-light, sans-serif, or DroidSans? – Jelle Fresen Jul 28 '15 at 14:05
  • since 5.0 you can, post an example in separate answer – gor Nov 24 '15 at 21:34
  • To use Roboto API level 16 is required otherwise, you will get an error. – Milon Mar 26 '16 at 14:33
  • So I guess the only font I can't get (without using the RobotoTextView library) is condensed light? right? – Demigod Aug 03 '16 at 16:05
  • How about Noto family? I cant find a way to make my app use Noto as default font family – KasparTr Aug 08 '16 at 19:03
  • List is also available here: http://androidxref.com/6.0.1_r10/xref/frameworks/base/data/fonts/system_fonts.xml – scorpiodawg Jan 19 '17 at 19:17
  • You can check out this project, for checking font compatibility on TextViews and in WebViews on different platform versions https://github.com/JeppeLeth/android_font_compat_tester – Jeppe Leth Apr 12 '17 at 06:54
  • sans-serif-medium is not available in my case – Akshatha Srinivas Aug 23 '17 at 11:08
  • 1
    Please, modify your answer - add android:fontFamily="sans-serif-bold" which corresponds to Roboto-bold. Thanks – Anton Kizema Oct 24 '18 at 16:20
  • Well this is not working for CJK :( Any other ideas? – Tsung Goh Nov 06 '18 at 19:32
  • And also, android:fontFamily="casual" – Akanshi Srivastava Oct 09 '19 at 07:07
  • there's a link for a full view of Roboto: https://fonts.google.com/specimen/Roboto – superuser Apr 17 '20 at 10:44
230

This is the way to set the font programmatically:

TextView tv = (TextView) findViewById(R.id.appname);
Typeface face = Typeface.createFromAsset(getAssets(),
            "fonts/epimodem.ttf");
tv.setTypeface(face);

put the font file in your assets folder. In my case I created a subdirectory called fonts.

EDIT: If you wonder where is your assets folder see this question

Community
  • 1
  • 1
s_bei
  • 11,895
  • 8
  • 47
  • 67
  • 38
    While this does work, please note that [this can create a memory leak](https://code.google.com/p/android/issues/detail?id=9904). It can be fixed using [this answer](https://stackoverflow.com/a/16902532/823952). – Charles Madere Mar 06 '14 at 18:54
  • @ScootrNova i get this error when i use your solution. Error : Font asset not found gothic.ttf – Sagar Devanga Dec 30 '14 at 08:24
  • How to apply this to whole app? Right now in example you are applying it only on on textview – Pritish Joshi Feb 06 '16 at 09:54
221

Starting from Android-Studio 3.0 its very easy to change font family

Using support library 26, it will work on devices running Android API version 16 and higher

Create a folder font under res directory .Download the font which ever you want and paste it inside font folder. The structure should be some thing like below

Here

Note: As of Android Support Library 26.0, you must declare both sets of attributes ( android: and app: ) to ensure your fonts load on devices running Api 26 or lower.

Now you can change font in layout using

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/dancing_script"
app:fontFamily="@font/dancing_script"/>

To change Programatically

 Typeface typeface = getResources().getFont(R.font.myfont);
   //or to support all versions use
Typeface typeface = ResourcesCompat.getFont(context, R.font.myfont);
 textView.setTypeface(typeface);  

To change font using styles.xml create a style

 <style name="Regular">
        <item name="android:fontFamily">@font/dancing_script</item>
        <item name="fontFamily">@font/dancing_script</item>
        <item name="android:textStyle">normal</item>
 </style>

and apply this style to TextView

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="@style/Regular"/>

you can also Create your own font family

- Right-click the font folder and go to New > Font resource file. The New Resource File window appears.

- Enter the file name, and then click OK. The new font resource XML opens in the editor.

Write your own font family here , for example

<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@font/lobster_regular" />
    <font
        android:fontStyle="italic"
        android:fontWeight="400"
        android:font="@font/lobster_italic" />
</font-family>

this is simply a mapping of a specific fontStyle and fontWeight to the font resource which will be used to render that specific variant. Valid values for fontStyle are normal or italic; and fontWeight conforms to the CSS font-weight specification

1. To change fontfamily in layout you can write

 <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/lobster"/>

2. To Change Programmatically

 Typeface typeface = getResources().getFont(R.font.lobster);
   //or to support all versions use
Typeface typeface = ResourcesCompat.getFont(context, R.font.lobster);
 textView.setTypeface(typeface);  

To change font of entire App Add these two lines in AppTheme

 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
     <item name="android:fontFamily">@font/your_font</item>
     <item name="fontFamily">@font/your_font</item>
  </style>

See the Documentation , Android Custom Fonts Tutorial For more info

Manohar Reddy
  • 15,894
  • 7
  • 77
  • 109
  • 7
    NB: This currently only works in Android Studio 3.0 Preview. It did not work for me on Android Studio 2.3.3. Hope that saves someone some time! – Tash Pemhiwa Jun 26 '17 at 14:51
  • 3
    How could you get the font from within a fragment since you can't just do `getResources()`? **EDIT**: This line at the end of your answer worked for me: `Typeface typeface = ResourcesCompat.getFont(context, R.font.myfont);` – Paradox Feb 11 '18 at 22:29
  • Somehow it made font look corrupted in my case, comparing to Caligtraphy. Also fontWeight doesn't do anything – Leo Droidcoder May 03 '18 at 11:16
  • @LeoDroidcoder it does work , make sure you used both `android:fontWeight` and `app:fontWeight` – Manohar Reddy May 03 '18 at 12:30
  • I checked several times. There is no effect. – Leo Droidcoder May 03 '18 at 13:07
  • Note that `xmlns:app="http://schemas.android.com/apk/res-auto"` must be included in your root element declaration to ensure it doesn't throw the error "Namespace 'app' not bound" – jungledev Sep 28 '18 at 12:43
  • 1
    Right-click main, select 'New', select 'Android Resource File'. In popup window type 'font' for name, select 'Font' from drop-down 'Resource Type' list. Click 'OK'. – Androidcoder May 17 '21 at 15:12
  • @Manohar How to use it in conjunction with a Textvo – Sharan May 25 '21 at 15:17
105

I had to parse /system/etc/fonts.xml in a recent project. Here are the current font families as of Lollipop:

╔════╦════════════════════════════╦═════════════════════════════╗
║    ║ FONT FAMILY                ║ TTF FILE                    ║
╠════╬════════════════════════════╬═════════════════════════════╣
║  1 ║ casual                     ║ ComingSoon.ttf              ║
║  2 ║ cursive                    ║ DancingScript-Regular.ttf   ║
║  3 ║ monospace                  ║ DroidSansMono.ttf           ║
║  4 ║ sans-serif                 ║ Roboto-Regular.ttf          ║
║  5 ║ sans-serif-black           ║ Roboto-Black.ttf            ║
║  6 ║ sans-serif-condensed       ║ RobotoCondensed-Regular.ttf ║
║  7 ║ sans-serif-condensed-light ║ RobotoCondensed-Light.ttf   ║
║  8 ║ sans-serif-light           ║ Roboto-Light.ttf            ║
║  9 ║ sans-serif-medium          ║ Roboto-Medium.ttf           ║
║ 10 ║ sans-serif-smallcaps       ║ CarroisGothicSC-Regular.ttf ║
║ 11 ║ sans-serif-thin            ║ Roboto-Thin.ttf             ║
║ 12 ║ serif                      ║ NotoSerif-Regular.ttf       ║
║ 13 ║ serif-monospace            ║ CutiveMono.ttf              ║
╚════╩════════════════════════════╩═════════════════════════════╝

Here is the parser (based off FontListParser):

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Xml;

/**
 * Helper class to get the current font families on an Android device.</p>
 * 
 * Usage:</p> {@code List<SystemFont> fonts = FontListParser.safelyGetSystemFonts();}</p>
 */
public final class FontListParser {

    private static final File FONTS_XML = new File("/system/etc/fonts.xml");

    private static final File SYSTEM_FONTS_XML = new File("/system/etc/system_fonts.xml");

    public static List<SystemFont> getSystemFonts() throws Exception {
        String fontsXml;
        if (FONTS_XML.exists()) {
            fontsXml = FONTS_XML.getAbsolutePath();
        } else if (SYSTEM_FONTS_XML.exists()) {
            fontsXml = SYSTEM_FONTS_XML.getAbsolutePath();
        } else {
            throw new RuntimeException("fonts.xml does not exist on this system");
        }
        Config parser = parse(new FileInputStream(fontsXml));
        List<SystemFont> fonts = new ArrayList<>();

        for (Family family : parser.families) {
            if (family.name != null) {
                Font font = null;
                for (Font f : family.fonts) {
                    font = f;
                    if (f.weight == 400) {
                        break;
                    }
                }
                SystemFont systemFont = new SystemFont(family.name, font.fontName);
                if (fonts.contains(systemFont)) {
                    continue;
                }
                fonts.add(new SystemFont(family.name, font.fontName));
            }
        }

        for (Alias alias : parser.aliases) {
            if (alias.name == null || alias.toName == null || alias.weight == 0) {
                continue;
            }
            for (Family family : parser.families) {
                if (family.name == null || !family.name.equals(alias.toName)) {
                    continue;
                }
                for (Font font : family.fonts) {
                    if (font.weight == alias.weight) {
                        fonts.add(new SystemFont(alias.name, font.fontName));
                        break;
                    }
                }
            }
        }

        if (fonts.isEmpty()) {
            throw new Exception("No system fonts found.");
        }

        Collections.sort(fonts, new Comparator<SystemFont>() {

            @Override
            public int compare(SystemFont font1, SystemFont font2) {
                return font1.name.compareToIgnoreCase(font2.name);
            }

        });

        return fonts;
    }

    public static List<SystemFont> safelyGetSystemFonts() {
        try {
            return getSystemFonts();
        } catch (Exception e) {
            String[][] defaultSystemFonts = {
                    {
                            "cursive", "DancingScript-Regular.ttf"
                    }, {
                            "monospace", "DroidSansMono.ttf"
                    }, {
                            "sans-serif", "Roboto-Regular.ttf"
                    }, {
                            "sans-serif-light", "Roboto-Light.ttf"
                    }, {
                            "sans-serif-medium", "Roboto-Medium.ttf"
                    }, {
                            "sans-serif-black", "Roboto-Black.ttf"
                    }, {
                            "sans-serif-condensed", "RobotoCondensed-Regular.ttf"
                    }, {
                            "sans-serif-thin", "Roboto-Thin.ttf"
                    }, {
                            "serif", "NotoSerif-Regular.ttf"
                    }
            };
            List<SystemFont> fonts = new ArrayList<>();
            for (String[] names : defaultSystemFonts) {
                File file = new File("/system/fonts", names[1]);
                if (file.exists()) {
                    fonts.add(new SystemFont(names[0], file.getAbsolutePath()));
                }
            }
            return fonts;
        }
    }

    /* Parse fallback list (no names) */
    public static Config parse(InputStream in) throws XmlPullParserException, IOException {
        try {
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(in, null);
            parser.nextTag();
            return readFamilies(parser);
        } finally {
            in.close();
        }
    }

    private static Alias readAlias(XmlPullParser parser) throws XmlPullParserException, IOException {
        Alias alias = new Alias();
        alias.name = parser.getAttributeValue(null, "name");
        alias.toName = parser.getAttributeValue(null, "to");
        String weightStr = parser.getAttributeValue(null, "weight");
        if (weightStr == null) {
            alias.weight = 0;
        } else {
            alias.weight = Integer.parseInt(weightStr);
        }
        skip(parser); // alias tag is empty, ignore any contents and consume end tag
        return alias;
    }

    private static Config readFamilies(XmlPullParser parser) throws XmlPullParserException,
            IOException {
        Config config = new Config();
        parser.require(XmlPullParser.START_TAG, null, "familyset");
        while (parser.next() != XmlPullParser.END_TAG) {
            if (parser.getEventType() != XmlPullParser.START_TAG) {
                continue;
            }
            if (parser.getName().equals("family")) {
                config.families.add(readFamily(parser));
            } else if (parser.getName().equals("alias")) {
                config.aliases.add(readAlias(parser));
            } else {
                skip(parser);
            }
        }
        return config;
    }

    private static Family readFamily(XmlPullParser parser) throws XmlPullParserException,
            IOException {
        String name = parser.getAttributeValue(null, "name");
        String lang = parser.getAttributeValue(null, "lang");
        String variant = parser.getAttributeValue(null, "variant");
        List<Font> fonts = new ArrayList<Font>();
        while (parser.next() != XmlPullParser.END_TAG) {
            if (parser.getEventType() != XmlPullParser.START_TAG) {
                continue;
            }
            String tag = parser.getName();
            if (tag.equals("font")) {
                String weightStr = parser.getAttributeValue(null, "weight");
                int weight = weightStr == null ? 400 : Integer.parseInt(weightStr);
                boolean isItalic = "italic".equals(parser.getAttributeValue(null, "style"));
                String filename = parser.nextText();
                String fullFilename = "/system/fonts/" + filename;
                fonts.add(new Font(fullFilename, weight, isItalic));
            } else {
                skip(parser);
            }
        }
        return new Family(name, fonts, lang, variant);
    }

    private static void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
        int depth = 1;
        while (depth > 0) {
            switch (parser.next()) {
            case XmlPullParser.START_TAG:
                depth++;
                break;
            case XmlPullParser.END_TAG:
                depth--;
                break;
            }
        }
    }

    private FontListParser() {

    }

    public static class Alias {

        public String name;

        public String toName;

        public int weight;
    }

    public static class Config {

        public List<Alias> aliases;

        public List<Family> families;

        Config() {
            families = new ArrayList<Family>();
            aliases = new ArrayList<Alias>();
        }

    }

    public static class Family {

        public List<Font> fonts;

        public String lang;

        public String name;

        public String variant;

        public Family(String name, List<Font> fonts, String lang, String variant) {
            this.name = name;
            this.fonts = fonts;
            this.lang = lang;
            this.variant = variant;
        }

    }

    public static class Font {

        public String fontName;

        public boolean isItalic;

        public int weight;

        Font(String fontName, int weight, boolean isItalic) {
            this.fontName = fontName;
            this.weight = weight;
            this.isItalic = isItalic;
        }

    }

    public static class SystemFont {

        public String name;

        public String path;

        public SystemFont(String name, String path) {
            this.name = name;
            this.path = path;
        }

    }
}

Feel free to use the above class in your project. For example, you could give your users a selection of font families and set the typeface based on their preference.

A small incomplete example:

final List<FontListParser.SystemFont> fonts = FontListParser.safelyGetSystemFonts();
String[] items = new String[fonts.size()];
for (int i = 0; i < fonts.size(); i++) {
    items[i] = fonts.get(i).name;
}

new AlertDialog.Builder(this).setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        FontListParser.SystemFont selectedFont = fonts.get(which);
        // TODO: do something with the font
        Toast.makeText(getApplicationContext(), selectedFont.path, Toast.LENGTH_LONG).show();
    }
}).show();
Jared Rummler
  • 35,743
  • 18
  • 127
  • 142
  • Do you know perhaps which version of Android added which font? – android developer Apr 23 '15 at 21:47
  • @androiddeveloper I don't. You could probably find out by viewing the changes here: https://github.com/android/platform_frameworks_base/blob/lollipop-release/data/fonts/system_fonts.xml – Jared Rummler Apr 23 '15 at 23:22
  • @JaredRummler, forgive my ignorance. Why/What is weight==400 ? – Samuel Sep 29 '16 at 02:03
  • 1
    @Samuel I haven't looked at this code in a while, but 400 font weight is used for "normal" or "regular" fonts. Example, Roboto-Regular has a weight of 400. – Jared Rummler Sep 29 '16 at 05:55
  • Does this require root or something? I ran this code on the Android emulator (version 8.1), and when I called `getSystemFonts()`, I got an exception `org.xmlpull.v1.XmlPullParserException: END_TAG expected (position:START_TAG (empty) @219:51 in java.io.InputStreamReader@f001fb3) ` – Damn Vegetables Mar 14 '18 at 13:55
  • Can anyone explain how each TTF file was mapped as the default for each font family? For example, for sans-serif, why is it that Roboto-Regular was the TTF file used? I see many files listed in this font family. Why was this particular one chosen over the others? – coolDude Mar 26 '19 at 22:19
  • Okay, I see that you used a weight of 400 as a threshold to determine the default font. Why 400 though? – coolDude Mar 26 '19 at 22:19
51

Android doesn't allow you to set custom fonts from the XML layout. Instead, you must bundle the specific font file in your app's assets folder, and set it programmatically. Something like:

TextView textView = (TextView) findViewById(<your TextView ID>);
Typeface typeFace = Typeface.createFromAsset(getAssets(), "<file name>");
textView.setTypeface(typeFace);

Note that you can only run this code after setContentView() has been called. Also, only some fonts are supported by Android, and should be in a .ttf (TrueType) or .otf (OpenType) format. Even then, some fonts may not work.

This is a font that definitely works on Android, and you can use this to confirm that your code is working in case your font file isn't supported by Android.

Android O Update: This is now possible with XML in Android O, based on Roger's comment.

Community
  • 1
  • 1
Raghav Sood
  • 79,170
  • 20
  • 177
  • 186
  • "Android doesn't allow you to set custom fonts from the XML layout." This has been changed in Android O, which allows you to create customized font family and apply them in XML: https://developer.android.com/preview/features/working-with-fonts.html – Roger Huang Apr 26 '17 at 09:26
31

To set Roboto programmatically:

paint.setTypeface(Typeface.create("sans-serif-thin", Typeface.NORMAL));
Oded Breiner
  • 25,024
  • 9
  • 99
  • 66
28

If you want it programatically, you could use

label.setTypeface(Typeface.SANS_SERIF, Typeface.ITALIC);

Where SANS_SERIF you can use:

  • DEFAULT
  • DEFAULT_BOLD
  • MONOSPACE
  • SANS_SERIF
  • SERIF

And where ITALIC you can use:

  • BOLD
  • BOLD_ITALIC
  • ITALIC
  • NORMAL

All is stated on Android Developers

Joaquin Iurchuk
  • 5,003
  • 1
  • 40
  • 61
25

It's the same as android:typeface.

built-in fonts are:

  • normal
  • sans
  • serif
  • monospace

See android:typeface.

biegleux
  • 12,934
  • 11
  • 42
  • 52
  • 4
    I don't think it is the same thing, but it does appear that we can't use both. It seems that there are now no less than three different attributes mapped to ``setTypeface()``. Namely ``fontFamily``, ``typeface`` and ``textStyle``. But I can't for the life of me figure out how these are precisely combined to resolve a concrete Typeface instance. Has anyone figured this out? Google's documentation is less than helpful... – Rad Haring Mar 06 '14 at 15:06
16
Typeface typeface = ResourcesCompat.getFont(context, R.font.font_name);
textView.setTypeface(typeface);

set easily font to any textview from res>font directory programmatically

Makvin
  • 2,719
  • 20
  • 22
15

I am using excellent library Calligraphy by Chris Jenx designed to allow you to use custom fonts in your android application. Give it a try!

gauravdott
  • 400
  • 1
  • 4
  • 14
15

I think I am too late but maybe this solution helpful for others. For using custom font place your font file in your font directory.

textView.setTypeface(ResourcesCompat.getFont(this, R.font.lato));
Rehan Sarwar
  • 904
  • 7
  • 20
15

Kotlin Code - Textview to set custom font from Resource Folder

Set custom font from res -> font -> avenir_next_regular.ttf

textView!!.typeface = ResourcesCompat.getFont(context!!, R.font.avenir_next_regular)
Pratik Dodiya
  • 559
  • 4
  • 8
12

What you want is not possible. You must need to set TypeFace in your Code.

In XML what you can do is

android:typeface="sans" | "serif" | "monospace"

other then this you can not play much with the Fonts in XML. :)

For Arial you need to set type face in your code.

Mohsin Naeem
  • 12,147
  • 3
  • 35
  • 52
11

An easy way to manage the fonts would be to declare them via resources, as such:

<!--++++++++++++++++++++++++++-->
<!--added on API 16 (JB - 4.1)-->
<!--++++++++++++++++++++++++++-->
<!--the default font-->
<string name="fontFamily__roboto_regular">sans-serif</string>
<string name="fontFamily__roboto_light">sans-serif-light</string>
<string name="fontFamily__roboto_condensed">sans-serif-condensed</string>

<!--+++++++++++++++++++++++++++++-->
<!--added on API 17 (JBMR1 - 4.2)-->
<!--+++++++++++++++++++++++++++++-->
<string name="fontFamily__roboto_thin">sans-serif-thin</string>

<!--+++++++++++++++++++++++++++-->
<!--added on Lollipop (LL- 5.0)-->
<!--+++++++++++++++++++++++++++-->
<string name="fontFamily__roboto_medium">sans-serif-medium</string>
<string name="fontFamily__roboto_black">sans-serif-black</string>
<string name="fontFamily__roboto_condensed_light">sans-serif-condensed-light</string>

This is based on the source code here and here

android developer
  • 106,412
  • 122
  • 641
  • 1,128
  • Where to declare them? – AZ_ May 20 '15 at 03:24
  • @AZ_ Just like many resource files, you can put it in any XML file you wish, inside the "res/values/" folder . For example, put it in "res/values/fonts.xml" . And, to use it, do simply like this for example : android:fontFamily="string/fontFamily__roboto_regular" – android developer May 20 '15 at 05:18
  • Thanks, I am using this https://github.com/norbsoft/android-typeface-helper and it's really helpful – AZ_ May 21 '15 at 04:19
  • ok, the library is probably for doing it programmatically. here it's for XML – android developer May 21 '15 at 06:24
10

One simple way is by adding the desired font in the project.

Go to File->New->New Resource Directory Select font

This will create a new directory, font, in your resources.

Download your font (.ttf). I use https://fonts.google.com for the same

Add that to your fonts folder then use them in the XML or programmatically.

XML -

<TextView 
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/your_font"/>

Programatically -

 Typeface typeface = ResourcesCompat.getFont(this, R.font.your_font);
 textView.setTypeface(typeface); 
Kishan Solanki
  • 8,893
  • 2
  • 51
  • 54
9

Dynamically you can set the fontfamily similar to android:fontFamily in xml by using this,

For Custom font:

 TextView tv = ((TextView) v.findViewById(R.id.select_item_title));
 Typeface face=Typeface.createFromAsset(getAssets(),"fonts/mycustomfont.ttf"); 
 tv.setTypeface(face);

For Default font:

 tv.setTypeface(Typeface.create("sans-serif-medium",Typeface.NORMAL));

These are the list of default font family used, use any of this by replacing the double quotation string "sans-serif-medium"

FONT FAMILY                    TTF FILE                    

1  casual                      ComingSoon.ttf              
2  cursive                     DancingScript-Regular.ttf   
3  monospace                   DroidSansMono.ttf           
4  sans-serif                  Roboto-Regular.ttf          
5  sans-serif-black            Roboto-Black.ttf            
6  sans-serif-condensed        RobotoCondensed-Regular.ttf 
7  sans-serif-condensed-light  RobotoCondensed-Light.ttf   
8  sans-serif-light            Roboto-Light.ttf            
9  sans-serif-medium           Roboto-Medium.ttf           
10  sans-serif-smallcaps       CarroisGothicSC-Regular.ttf 
11  sans-serif-thin            Roboto-Thin.ttf             
12  serif                      NotoSerif-Regular.ttf       
13  serif-monospace            CutiveMono.ttf              

"mycustomfont.ttf" is the ttf file. Path will be in src/assets/fonts/mycustomfont.ttf , you can refer more about default font in this Default font family

anand krish
  • 3,029
  • 4
  • 32
  • 43
6

With some trial and error I learned the following.

Within the *.xml you can combine the stock fonts with the following functions, not only with typeface:

 android:fontFamily="serif" 
 android:textStyle="italic"

With this two styles, there was no need to use typeface in any other case. The range of combinations is much more bigger with fontfamily&textStyle.

5

The valid value of android:fontFamily is defined in /system/etc/system_fonts.xml(4.x) or /system/etc/fonts.xml(5.x). But Device Manufacturer might modify it, so the actual font used by setting fontFamily value depends on the above-mentioned file of the specified device.

In AOSP, the Arial font is valid but must be defined using "arial" not "Arial", for example android:fontFamily="arial". Have a qucik look at Kitkat's system_fonts.xml

    <family>
    <nameset>
        <name>sans-serif</name>
        <name>arial</name>
        <name>helvetica</name>
        <name>tahoma</name>
        <name>verdana</name>
    </nameset>
    <fileset>
        <file>Roboto-Regular.ttf</file>
        <file>Roboto-Bold.ttf</file>
        <file>Roboto-Italic.ttf</file>
        <file>Roboto-BoldItalic.ttf</file>
    </fileset>
</family>

//////////////////////////////////////////////////////////////////////////

There are three relevant xml-attributes for defining a "font" in layout--android:fontFamily, android:typeface and android:textStyle. The combination of "fontFamily" and "textStyle" or "typeface" and "textStyle" can be used to change the appearance of font in text, so does used alone. Code snippet in TextView.java like this:

    private void setTypefaceFromAttrs(String familyName, int typefaceIndex, int styleIndex) {
    Typeface tf = null;
    if (familyName != null) {
        tf = Typeface.create(familyName, styleIndex);
        if (tf != null) {
            setTypeface(tf);
            return;
        }
    }
    switch (typefaceIndex) {
        case SANS:
            tf = Typeface.SANS_SERIF;
            break;

        case SERIF:
            tf = Typeface.SERIF;
            break;

        case MONOSPACE:
            tf = Typeface.MONOSPACE;
            break;
    }
    setTypeface(tf, styleIndex);
}


    public void setTypeface(Typeface tf, int style) {
    if (style > 0) {
        if (tf == null) {
            tf = Typeface.defaultFromStyle(style);
        } else {
            tf = Typeface.create(tf, style);
        }

        setTypeface(tf);
        // now compute what (if any) algorithmic styling is needed
        int typefaceStyle = tf != null ? tf.getStyle() : 0;
        int need = style & ~typefaceStyle;
        mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0);
        mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0);
    } else {
        mTextPaint.setFakeBoldText(false);
        mTextPaint.setTextSkewX(0);
        setTypeface(tf);
    }
}

From the code We can see:

  1. if "fontFamily" is set, then the "typeface" will be ignored.
  2. "typeface" has standard and limited valid values. In fact, the values are "normal" "sans" "serif" and "monospace", they can be found in system_fonts.xml(4.x) or fonts.xml(5.x). Actually both "normal" and "sans" are the default font of system.
  3. "fontFamily" can be used to set all fonts of build-in fonts, while "typeface" only provide the typical fonts of "sans-serif" "serif" and "monospace"(the three main category of font type in the world).
  4. When only set "textStyle", We actually set the default font and the specified style. The effective value are "normal" "bold" "italic" and "bold | italic".
Terry Liu
  • 601
  • 5
  • 8
5

If you are using Android Studio 3.5+, Changing font is super simple. Select the text widget on Design view and check fontFamily on Attribute Window. The value dropdown contains all the available fonts from which you can select one. If you are looking for Google Fonts, Click More Fonts option.

Attribute Window Attribute Window

Google Fonts Google Fonts

Siva
  • 116
  • 3
  • 4
5

You can also do this by adding a font folder under the res directory like below.

enter image description here

Then, selecting Font as the resource type. enter image description here

You can find avaliable fonts from https://www.1001fonts.com/, and then extracting the TTF files to this font directory.

enter image description here

Finally, just change the XML file that contains your textview by adding android:fontFamily:"@font/urfontfilename"

enter image description here

Wolfiebae
  • 325
  • 4
  • 17
  • very nice, thank you for this. idk why others have more stars but yours is confirmed to work with material design text view, you must use `app:fontFamily=` however, everything else is the same. – EvOlaNdLuPiZ Mar 02 '20 at 00:23
  • YOu saved my life, I had just created a folder named font and it did not work. Anyway I used your way and it worked.Thanks – Hilal May 23 '20 at 04:42
4

Here is an easier way that can work in some cases. The principle is to add a not visible TextVview in your xml layout and to get its typeFace in the java code.

The layout in the xml file:

 <TextView
        android:text="The classic bread is made of flour hot and salty. The classic bread is made of flour hot and salty. The classic bread is made of flour hot and salty."
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fontFamily="sans-serif-thin"
        android:id="@+id/textViewDescription"/>

And the java code:

myText.setTypeface(textViewSelectedDescription.getTypeface());

It has worked for me (within a TextSwitcher for example).

Frédéric
  • 77
  • 2
4

Try this:

TextView textview = (TextView) findViewById(R.id.textview);

Typeface tf= Typeface.createFromAsset(getAssets(),"fonts/Tahoma.ttf");
textview .setTypeface(tf);
mohamad sheikhi
  • 304
  • 3
  • 14
4

To set the font by program, write...

     TextView tv7 = new TextView(this);
     tv7.setText(" TIME ");    
     tv7.setTypeface(Typeface.create("sans-serif-condensed",Typeface.BOLD));
     tv7.setTextSize(12);
     tbrow.addView(tv7);

The name "sans-serif-condensed" is referenced from fonts.xml file which should be created in app--> res--> values folder and it holds the fonts in it.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="font_family_light">sans-serif-light</string>
    <string name="font_family_medium">sans-serif-medium</string>
    <string name="font_family_regular">sans-serif</string>
    <string name="font_family_condensed">sans-serif-condensed</string>
    <string name="font_family_black">sans-serif-black</string>
    <string name="font_family_thin">sans-serif-thin</string>
</resources>

Hope this is clear!

MdBasha
  • 403
  • 1
  • 13
3
<string name="font_family_display_4_material">sans-serif-light</string>
<string name="font_family_display_3_material">sans-serif</string>
<string name="font_family_display_2_material">sans-serif</string>
<string name="font_family_display_1_material">sans-serif</string>
<string name="font_family_headline_material">sans-serif</string>
<string name="font_family_title_material">sans-serif-medium</string>
<string name="font_family_subhead_material">sans-serif</string>
<string name="font_family_menu_material">sans-serif</string>
<string name="font_family_body_2_material">sans-serif-medium</string>
<string name="font_family_body_1_material">sans-serif</string>
<string name="font_family_caption_material">sans-serif</string>
<string name="font_family_button_material">sans-serif-medium</string>
Yang Peiyong
  • 10,618
  • 2
  • 19
  • 14
3

If you want to use a TextView in so many places with same font family, extend the TextView class and set your font like this:-

public class ProximaNovaTextView extends TextView {

    public ProximaNovaTextView(Context context) {
        super(context);

        applyCustomFont(context);
    }

    public ProximaNovaTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        applyCustomFont(context);
    }

    public ProximaNovaTextView(Context context, AttributeSet attrs, int defStyle) {
       super(context, attrs, defStyle);

       applyCustomFont(context);
    } 

    private void applyCustomFont(Context context) {
        Typeface customFont = FontCache.getTypeface("proximanova_regular.otf", context);
        setTypeface(customFont);
    }
}

And then use this custom class in xml for the TextView like this:-

   <com.myapp.customview.ProximaNovaTextView
        android:id="@+id/feed_list_item_name_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        />
Shubham Raitka
  • 779
  • 3
  • 14
2

I just want to mention that the hell with the fonts inside Android is about to end, because this year on Google IO we finally got this -> https://developer.android.com/preview/features/working-with-fonts.html

Now there is a new resource type a font and you can place all your application fonts inside res/fonts folder and access then with R.font.my_custom_font, just like you can access string res values, drawable res values etc. You have even chance to create font-face xml file, which is gonna be set of your custom fonts (about italic, bold and underline attr).

Read the link above for more info. Let's see the support.

Stoycho Andreev
  • 5,468
  • 1
  • 23
  • 27
2

The new font resource allows to directly set font using

android:fontFamily="@font/my_font_in_font_folder"
Aziz
  • 1,092
  • 9
  • 16
1

You set style in res/layout/value/style.xml like that:

<style name="boldText">
    <item name="android:textStyle">bold|italic</item>
    <item name="android:textColor">#FFFFFF</item>
</style>

and to use this style in main.xml file use:

style="@style/boldText"
Ziem
  • 6,059
  • 7
  • 49
  • 83
rajender
  • 19
  • 1
1

For android-studio 3 and above you can use this style and then all textView font change in app.

create this style in your style.xml :

<!--OverRide all textView font-->
<style name="defaultTextViewStyle" parent="android:Widget.TextView">
        <item name="android:fontFamily">@font/your_custom_font</item>
</style>

Then use it in your theme :

<!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:textViewStyle">@style/defaultTextViewStyle</item>
    </style>
Ali Khaki
  • 1,082
  • 1
  • 10
  • 22
1

The easiest way to add the font programatically to a TextView is to, first, add the font file in your Assets folder in the project. For example your font path is looking like this: assets/fonts/my_font.otf

And add it to a TextView as:

Kotlin

val font_path = "fonts/my_font.otf"  

myTypeface = Typeface.createFromAsset(MyApplication.getInstance().assets, font_path)

textView.typeface = myTypeface

Java

String font_path = "fonts/my_font.otf";
Typeface myTypeface = Typeface.createFromAsset(MyApplication.getInstance().assets, font_path)
textView.setTypeface(myTypeface);
androidEnthusiast
  • 1,047
  • 1
  • 11
  • 20
1

There is a nice library available for this

    implementation 'uk.co.chrisjenx:calligraphy:2.3.0'
Shivam Yadav
  • 701
  • 5
  • 19
  • This library isu used to change font of all views in entire application. This is not applicable for adapter views such as list view. For that we need to add code in each adapter specifically – Senthilvel S Jul 25 '19 at 10:44
1

You can also change standard fonts with setTextAppearance (requires API 16), see https://stackoverflow.com/a/36301508/2914140:

<style name="styleA">
    <item name="android:fontFamily">sans-serif</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">?android:attr/textColorPrimary</item>
</style>
<style name="styleB">
    <item name="android:fontFamily">sans-serif-light</item>
    <item name="android:textStyle">normal</item>
    <item name="android:textColor">?android:attr/textColorTertiary</item>
</style>


if(condition){
    TextViewCompat.setTextAppearance(textView, R.style.styleA);
} else {
    TextViewCompat.setTextAppearance(textView,R.style.styleB);
}
CoolMind
  • 16,738
  • 10
  • 131
  • 165
1

You can define a custom FontFamily like this:

/res/font/usual.xml:

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:ignore="UnusedAttribute">
    <font
        android:fontStyle="normal"
        android:fontWeight="200"
        android:font="@font/usual_regular"
        app:fontStyle="normal"
        app:fontWeight="200"
        app:font="@font/usual_regular" />

    <font
        android:fontStyle="italic"
        android:fontWeight="200"
        android:font="@font/usual_regular_italic"
        app:fontStyle="italic"
        app:fontWeight="200"
        app:font="@font/usual_regular_italic" />

    <font
        android:fontStyle="normal"
        android:fontWeight="600"
        android:font="@font/usual_bold"
        app:fontStyle="normal"
        app:fontWeight="600"
        app:font="@font/usual_bold" />

    <font
        android:fontStyle="italic"
        android:fontWeight="600"
        android:font="@font/usual_bold_italic"
        app:fontStyle="italic"
        app:fontWeight="600"
        app:font="@font/usual_bold_italic" />
</font-family>

Now you can do

android:fontFamily="@font/usual"

Assuming your other font resources are there as well, with lowercase letters and _s.

EpicPandaForce
  • 71,034
  • 25
  • 221
  • 371
0

Here you can see all the avaliable fontFamily values and it's corresponding font file's names(This file is using in android 5.0+). In mobile device, you can find it in:

/system/etc/fonts.xml (for 5.0+)

(For android 4.4 and below using this version, but I think that fonts.xml has a more clear format and easy to understand.)

For example,

    <!-- first font is default -->
20    <family name="sans-serif">
21        <font weight="100" style="normal">Roboto-Thin.ttf</font>
22        <font weight="100" style="italic">Roboto-ThinItalic.ttf</font>
23        <font weight="300" style="normal">Roboto-Light.ttf</font>
24        <font weight="300" style="italic">Roboto-LightItalic.ttf</font>
25        <font weight="400" style="normal">Roboto-Regular.ttf</font>
26        <font weight="400" style="italic">Roboto-Italic.ttf</font>
27        <font weight="500" style="normal">Roboto-Medium.ttf</font>
28        <font weight="500" style="italic">Roboto-MediumItalic.ttf</font>
29        <font weight="900" style="normal">Roboto-Black.ttf</font>
30        <font weight="900" style="italic">Roboto-BlackItalic.ttf</font>
31        <font weight="700" style="normal">Roboto-Bold.ttf</font>
32        <font weight="700" style="italic">Roboto-BoldItalic.ttf</font>
33    </family>

The name attribute name="sans-serif" of family tag defined the value you can use in android:fontFamily.

The font tag define the corresponded font files.

In this case, you can ignore the source under <!-- fallback fonts -->, it's using for fonts' fallback logic.

Gnod
  • 147
  • 4
0

I use Letter Press lib for my NonTextView stuff like Buttons and kianoni fontloader lib for my TextViews cause of usage of style in this lib is more easy than Letter Press for me and i got ideal feedback with that. this is great for those who want to use custom font except Roboto Font. so it was my experience with font libs. for those who want to use custom class for change font i highly recommended to create this class with this snippet

    public class TypefaceSpan extends MetricAffectingSpan {
    /** An <code>LruCache</code> for previously loaded typefaces. */
    private static LruCache<String, Typeface> sTypefaceCache =
            new LruCache<String, Typeface>(12);

    private Typeface mTypeface;

    /**
     * Load the {@link android.graphics.Typeface} and apply to a {@link android.text.Spannable}.
     */
    public TypefaceSpan(Context context, String typefaceName) {
        mTypeface = sTypefaceCache.get(typefaceName);

        if (mTypeface == null) {
            mTypeface = Typeface.createFromAsset(context.getApplicationContext()
                    .getAssets(), String.format("fonts/%s", typefaceName));

            // Cache the loaded Typeface
            sTypefaceCache.put(typefaceName, mTypeface);
        }
    }

    @Override
    public void updateMeasureState(TextPaint p) {
        p.setTypeface(mTypeface);

        // Note: This flag is required for proper typeface rendering
        p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
    }

    @Override
    public void updateDrawState(TextPaint tp) {
        tp.setTypeface(mTypeface);

        // Note: This flag is required for proper typeface rendering
        tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
    }
}

And use class like this :

AppData = PreferenceManager.getDefaultSharedPreferences(this);
TextView bannertv= (TextView) findViewById(R.id.txtBanner);
    SpannableString s = new SpannableString(getResources().getString(R.string.enterkey));
    s.setSpan(new TypefaceSpan(this, AppData.getString("font-Bold",null)), 0, s.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    bannertv.setText(s);

maybe this help.

Ali Khaki
  • 1,082
  • 1
  • 10
  • 22
Setmax
  • 634
  • 5
  • 9
0

You can do it easy way by using following library

https://github.com/sunnag7/FontStyler

<com.sunnag.fontstyler.FontStylerView
              android:textStyle="bold"
              android:text="@string/about_us"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:paddingTop="8dp"
              app:fontName="Lato-Bold"
              android:textSize="18sp"
              android:id="@+id/textView64" />

its light weight and easy to implement, just copy your fonts in asset folder and use name in xml.

Sanny Nagveker
  • 390
  • 2
  • 7
0

try these simple steps. 1. create font folder in res folder. 2. copy and paste .ttf file into font folder. 3. Now give the path in xml like below.

 android:fontFamily="@font/frutiger"

or what ever your file name is. Thats it happy code

Syed Danish Haider
  • 1,126
  • 9
  • 14