Jakubee
Jakubee

Reputation: 634

How to Set a Custom Font Family in the Xamarin ActionBar Title?

As in title. I found the idea how to do this here Custom Fonts in Xamarin.Forms NavigationBar + ActionBar that tells to define this in style.xml file but I'm not able to get the custom font family.

So my style look like this right now:

 <style name="Toolbar.TitleText" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
<!--set your custom font properties-->
<item name="android:textSize">18sp</item>
<item name="android:fontFamily">HelveticaNeue Medium.ttf</item>
<item name="android:textColor">@android:color/white</item>

Upvotes: 3

Views: 2256

Answers (1)

Sparsha Bhattarai
Sparsha Bhattarai

Reputation: 703

You can create a custom renderer in android for this purpose. The renderer simply changes the typeface of your navigation bar using the resource defined in your android project. You can use the following renderer in android:

[assembly: ExportRenderer(typeof(NavigationPage), typeof(AndroidNavigationRenderer))]
namespace Xamarin.Droid.DependencyServices
{
  public class AndroidNavigationRenderer : 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;
        }
    }

    private void Toolbar_ChildViewAdded(object sender, ChildViewAddedEventArgs e)
    {
        var view = e.Child.GetType();
        if (e.Child.GetType() == typeof(Android.Support.V7.Widget.AppCompatTextView))
        {
            var textView = (Android.Support.V7.Widget.AppCompatTextView)e.Child;
            textView.Typeface = Typeface.CreateFromAsset(this.Context.Assets, "fonts/QuicksandRegular.ttf");

            toolbar.ChildViewAdded -= Toolbar_ChildViewAdded;
        }
    }
  }
}

For UWP, you can define a custom style in your app.xaml to override the default style of your title bar. You can use the following code in UWP:

 <Style x:Key="TitleTextBlockStyle" TargetType="TextBlock">
    <Setter Property="FontSize" Value="18"/>
    <Setter Property="FontStyle" Value="Normal"/>
    <Setter Property="FontWeight" Value="SemiBold"/>
    <Setter Property="FontFamily" Value="Assets/Fonts/QuicksandRegular.ttf#Quicksand"/>
    <Setter Property="Padding" Value="10"/>
 </Style>

Simply change the font family to the font family of your choice.

Upvotes: 6

Related Questions