Home » Android » In android How to applying font for whole application?

In android How to applying font for whole application?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I want to apply some font say Times New Roman to only my application.
Not to the whole system and not to specific view. As far I know

to apply font to specific view we store font file in asset folder and get into the application as follow.

1]  Typeface  mFace = Typeface.createFromAsset(getContext().getAssets(),
                                     "fonts/samplefont.ttf");
    textView.setTypeface(mFace);


2] To apply font to whole application I can replace the DroidSans.ttf file with my font file.

I can use first way to apply font to my application but It won’t be a good solution because I need to modify everywhere and I don’t want to do that if there is any better way is available.

How to&Answers:

Check this to define fonts styles. In addition, you can refer to this style from your manifest file at the app level

<application
    android:theme="@style/Theme1">

Answer:

I made a custom textview widget and in the constructors made a call to this code:

public static void SetCustomFont (TextView t, String fontName, Context c) {
        Typeface tf = Typeface.createFromAsset(c.getAssets(),
                fontName);
        t.setTypeface(tf);
}

I’m using the same font over the whole application so I put the fontName in the constuctor and then did a global Find/Replace for TextView

Answer:

Android does not provide much in the way of support for applying fonts across the whole app (see this issue). You have 4 options to set the font for the entire app:

  • Option1: Apply reflection to change the system font
  • Option2: Create and subclass custom View classes for each View that needs a custom font
  • Option3: Implement a View Crawler which traverses the view hierarchy for the current screen
  • Option4: Use a 3rd party library.

Details of these options can be found here.