Home > other >  Xamarin Forms: How to Change Navigation Title Font Family for Android?
Xamarin Forms: How to Change Navigation Title Font Family for Android?

Time:02-07

I'm working on a Xamarin Forms project using AppShell and Flyout. I want to change the font family of the navigation title. I tried to find ways to do it but unfortunately I could not solve this issue. One of my attempt from online solutions is to use a custom render using the code below. It gives me a warning that the NavigationPageRendereris Obsolete and when I run it, I get an exception. Please help me find a way to change the navigation title font family.

Custom Render:

[assembly: ExportRenderer(typeof(AppShell), typeof(CustomNavigationPageRenderer))]
namespace MyApp.Droid.CustomRenderers
{
    public class CustomNavigationPageRenderer : NavigationPageRenderer
    {
        private Android.Support.V7.Widget.Toolbar _toolbar;

        public override void OnViewAdded(Android.Views.View child)
        {
            base.OnViewAdded(child);

            if (child.GetType() == typeof(Android.Support.V7.Widget.Toolbar))
            {
                _toolbar = (Android.Support.V7.Widget.Toolbar)child;
                _toolbar.ChildViewAdded  = Toolbar_ChildViewAdded;
            }
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (disposing)
            {
                _toolbar.ChildViewAdded -= Toolbar_ChildViewAdded;
            }
        }

        private void Toolbar_ChildViewAdded(object sender, ChildViewAddedEventArgs e)
        {
            var view = e.Child.GetType();

            if (e.Child.GetType() == typeof(Android.Widget.TextView))
            {
                var textView = (Android.Widget.TextView)e.Child;
                var spaceFont = Typeface.CreateFromAsset(Forms.Context.ApplicationContext.Assets, "Montserrat-SemiBold.ttf");
                textView.Typeface = spaceFont;
                _toolbar.ChildViewAdded -= Toolbar_ChildViewAdded;
            }
        }
    }
}

Warning:

'NavigationPageRenderer.NavigationPageRenderer()' is obsolete: 'This constructor is obsolete as of version 2.5. Please use NavigationPageRenderer(Context) instead.

Exception Thrown: (at 'LoadApplication(new App())' in 'MainActivity' Class")

System.ArgumentException: 'element is not of type Xamarin.Forms.NavigationPage
Parameter name: element'

CodePudding user response:

Can you please try this. In your page that you want to change title font and after adding you costume fonts, Add this to the xaml. change the FontFamily to the font you want.

<NavigationPage.TitleView>
    <StackLayout>
        <Label FontFamily=""/>
    </StackLayout>
</NavigationPage.TitleView>
  •  Tags:  
  • Related