Skip to content Skip to sidebar Skip to footer

How To Change Font Style Or Override Default Font Style For Complete Application In Xamarin.android

I found many post saying to change font style of every label/entry/button/etc etc statically from xaml files using FontAttribute='Font_Syle.tff#Font_Style' or by making the custom

Solution 1:

Finally found a solution to do so, which can change the font of the complete application.

(There are many solutions for Java but none in C# soo posting it here, it might be helpful for someone in future)

Code Snippet

  1. Add this in Resource/values/style.xml. Remember to place it in the main parent STYLE of your App Theme.
<itemname="android:typeface">serif</item>
  1. Create the new file name TypefaceUtil in Droid project
using Android.Content;
using Android.Graphics;
using Java.Lang;

namespace ***********.Droid
{
    publicclassTypefaceUtil
    {

        /**
         * Using reflection to override default typeface
         * NOTICE: DO NOT FORGET TO SET TYPEFACE FOR APP THEME AS DEFAULT TYPEFACE WHICH WILL BE OVERRIDDEN
         * @param context to work with assets
         * @param defaultFontNameToOverride for example "monospace"
         * @param customFontFileNameInAssets file name of the font from assets
         */publicstaticvoidoverrideFont(Context context, string defaultFontNameToOverride, string customFontFileNameInAssets)
        {
            try
            {
                var typeFace = Class.FromType(typeof(Typeface));
                var customfont = Typeface.CreateFromAsset(context.Assets, customFontFileNameInAssets);
                var font = typeFace.GetDeclaredField(defaultFontNameToOverride);
                font.Accessible = true;
                font.Set(null, customfont);
            }
            catch (System.Exception e)
            {
                var error = e.Message;
            }
        }
    }
}
  1. In the MainActivity which extends Application, call the above-created method.
publicclassMainApplication : Application
{
   publicoverridevoidOnCreate()
        {
            base.OnCreate();
            TypefaceUtil.overrideFont(Context, "SERIF", "Montserrat_Regular.ttf"); // font from assets: "assets/fonts/Montserrat_Regular.ttf
   }
}

Note: Place your Font tff file in Asset folder of Resource

That's all, font is all set & ready to go :)

Post a Comment for "How To Change Font Style Or Override Default Font Style For Complete Application In Xamarin.android"