Is it possible to set a custom font for entire of application?

后端 未结 25 2701
日久生厌
日久生厌 2020-11-22 02:44

I need to use certain font for my entire application. I have .ttf file for the same. Is it possible to set this as default font, at application start up and then use it else

25条回答
  •  失恋的感觉
    2020-11-22 03:18

    Working for Xamarin.Android:

    Class:

    public class FontsOverride
    {
        public static void SetDefaultFont(Context context, string staticTypefaceFieldName, string fontAssetName)
        {
            Typeface regular = Typeface.CreateFromAsset(context.Assets, fontAssetName);
            ReplaceFont(staticTypefaceFieldName, regular);
        }
    
        protected static void ReplaceFont(string staticTypefaceFieldName, Typeface newTypeface)
        {
            try
            {
                Field staticField = ((Java.Lang.Object)(newTypeface)).Class.GetDeclaredField(staticTypefaceFieldName);
                staticField.Accessible = true;
                staticField.Set(null, newTypeface);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
    

    Application Implementation:

    namespace SomeAndroidApplication
    {
        [Application]
        public class App : Application
        {
            public App()
            {
    
            }
    
            public App(IntPtr handle, JniHandleOwnership transfer)
                : base(handle, transfer)
            {
    
            }
    
            public override void OnCreate()
            {
                base.OnCreate();
    
                FontsOverride.SetDefaultFont(this, "MONOSPACE", "fonts/Roboto-Light.ttf");
            }
        }
    }
    

    Style:

    
    

提交回复
热议问题