Creating font and text styles in android with Paint object

Use the TextPaint class instead of Paint. And can be implemented as below

TextPaint textPaint = new TextPaint();
textPaint.setTextSize(30);
textPaint.setTextAlign(Paint.Align.LEFT);
textPaint.setColor(Color.WHITE);
textPaint.setTypeface(Typeface.create("Arial", Typeface.BOLD));

Januari 2020

Copy the fonts you want to use to res/font (e.g. opensans_regular.ttf, opensans_italic.ttf, opensans_bolditalic.ttf, etc.) Watch out no '-' of capitals in the name!

Create New Font resource file opensans.xml

<?xml version="1.0" encoding="utf-8"?>
<font-family
     xmlns:app="http://schemas.android.com/apk/res-auto">

    <font
        app:fontStyle="normal"
        app:fontWeight="400"
        app:font="@font/opensans_regular" />

    <font
        app:fontStyle="italic"
        app:fontWeight="400"
        app:font="@font/opensans_italic" />

    <font
        app:fontStyle="normal"
        app:fontWeight="700"
        app:font="@font/opensans_bold" />

    <font
        app:fontStyle="italic"
        app:fontWeight="700"
        app:font="@font/opensans_bolditalic" />

    <font
        app:fontStyle="normal"
        app:fontWeight="200"
        app:font="@font/opensans_light" />

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

    <font
        app:fontStyle="normal"
        app:fontWeight="800"
        app:font="@font/opensans_extrabold" />

    <font
        app:fontStyle="italic"
        app:fontWeight="800"
        app:font="@font/opensans_extrabolditalic" />

</font-family>

In your MainActivity.java you can use the following code

    Paint paint = new Paint();
    Typeface typeface;

    if (Build.VERSION.SDK_INT >= 28) {
        // This does only works from SDK 28 and higher
        Typeface typefaceA = ResourcesCompat.getFont(this, R.font.opensans);
        typeface = Typeface.create(typefaceA, 700, false);
    } else {
        // This always works (Whole name without .ttf)
        typeface = ResourcesCompat.getFont(this, R.font.opensans_bolditalic);
    }
    paint.setTypeface(typeface);

Tags:

Java

Android