Xamarin.Forms custom Android NavigationPageRenderer title and subtitles

Currently working on a project where I want to use AppCompat, and most pages have title and subtitle requirements.

It does not work using AppCompat at all - neither setting properties, nor using custom views.

If using AppCompat does not work, as expected. The full source code is available here , so just run the application if you're interested :)

using System.ComponentModel; using Android.App; using Android.Widget; using App1.Droid.Renderers; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; #if __APPCOMPAT__ using NavigationRenderer = Xamarin.Forms.Platform.Android.AppCompat.NavigationPageRenderer; #else using NavigationRenderer = Xamarin.Forms.Platform.Android.NavigationRenderer; #endif [assembly: ExportRenderer(typeof(NavigationPage), typeof(NavigationPageRenderer))] namespace App1.Droid.Renderers { public class NavigationPageRenderer : NavigationRenderer { protected override void OnElementChanged(ElementChangedEventArgs<NavigationPage> e) { base.OnElementChanged(e); SetCustomView(e.NewElement.CurrentPage.GetType().Name); } private void SetCustomView(string view) { var activity = (Activity)Context; #if __APPCOMPAT__ var actionBar = ((FormsAppCompatActivity)Context).SupportActionBar; #else var actionBar = activity.ActionBar; #endif actionBar.Title = view; actionBar.Subtitle = " -> " + view; var abv = new LinearLayout(activity) { Orientation = Orientation.Vertical }; var main = new TextView(activity) { Text = view, }; main.SetTextColor(Color.Aqua.ToAndroid()); main.SetPadding(4, 4, 2, 6); abv.AddView(main); abv.AddView(new TextView(activity) { Text = " -> " + view }); actionBar.SetDisplayShowCustomEnabled(true); actionBar.CustomView = abv; } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName.Equals("CurrentPage")) { SetCustomView(((NavigationPage)sender).CurrentPage.GetType().Name); } } } } 

Edit: Thanks @jimmgarr. Slightly changed the code so that the rotation between AppCompbat and "normal mode". Code is available here.

+5
source share
1 answer

So, it seems that NavigationPage uses its own instance of the toolbar . Therefore setting properties on a SupportActionBar does nothing.

I managed to get it working by overriding OnViewAdded() to get a link to the new toolbar when it was added:

 public override void OnViewAdded(Android.Views.View child) { base.OnViewAdded(child); if (child.GetType() == typeof(Support.Toolbar)) toolbar = (Support.Toolbar)child; } 

Then, using the link inside SetCustomView() , set only Subtitle, since Title is already installed automatically.

Here's the full rendering class :)

+6
source

All Articles