Font in TextView Android

Question:

I am dynamically creating a TextView. You need to install the font that the rest of the program uses. When this code is called, the application crashes.

            TextView textDis = new TextView(this.getContext());
            textDis.setPadding(16, 16, 16, 16);
            textDis.setTextColor(getResources().getColor(R.color.colorBlack));
            textDis.setTextSize(18);
            //Ошибочный код ниже:
            textDis.setTypeface(getResources().getFont(R.font.fira_sans), Typeface.BOLD);

Thanks for the help!

Answer:

For fonts, I recommend using the assets folder and installing like this:

textDis.setTypeface(Typeface.createFromAsset(getAssets(), "my_font_bold.ttf");

In addition, to avoid lags (and if you have a lot of texts with your own font, they will be), I recommend caching the font, for example:

public class TypeFaces {

    //---Кэширование шрифта---
    private static final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>();

    public static Typeface get(Context c, int type) {
        String name;
        if (type == 1)
            name = "my_font.ttf";
        else
            name = "my_font_bold.ttf";

        synchronized (cache) {
            if (!cache.containsKey(name)) {
                String path = name;
                try {
                    Typeface t = Typeface.createFromAsset(c.getAssets(), path);
                    cache.put(name, t);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return cache.get(name);
        }
    }
}

And use like this:

 textDis.setTypeface(TypeFaces.get(this, 2));

If you have a lot of text, the best option would be to create a custom TextView , where in init() font will be set automatically.

Or you can use the method from the support library :

textDis.setTypeface(ResourcesCompat.getFont(context, R.font.my_font));
Scroll to Top