Set a custom toolbar .NET Maui Android

681 views Asked by At

I am trying to update a Xamarin.Forms application to .NET MAUI, and I am currently stuck trying to port over the NavigationPageRenderer for Android. In .NET 7 it seems to not work at all, saying that it cannot convert the google.android.material toolbar to androidx.appcompat.widget.toolbar.

So I tried porting over to handlers. Specifically, the NavigationViewHandler. I am able to get the toolbar information using this:

var layout = MainActivity.Activity.FindViewById<LinearLayout>(Resource.Id.navigationlayout_appbar);

Toolbar toolbar = layout.GetChildAt(0);

This works, but the issue I have is I cannot set a custom toolbar.

I have inside Platforms/Android/Resources/layout a Toolbar.axml file, but inside OnCreate method, FindViewById(Resource.Id.toolbar) returns null.

In Xamarin.Forms doing this was easy, since there was the ToolbarResource property, which would be set to the layout of the toolbar, and all would work fine.

Any help would be appreciated.

Thank you!

1

There are 1 answers

0
Dorian Olarescu On

I was not able to replace the toolbar, but I have found a way to modify it. For anyone that is stuck on this, this helped me:

public class CustomNavigationPageHandler : NavigationViewHandler
{

   protected override void ConnectHandler(View platformView)
   {
       base.ConnectHandler(platformView);
          
       SetCustomFontTitle(platformView);
   }

     private void SetCustomFontTitle(View platformView)
     {
         // This is the toolbar
         var toolbar = ((LinearLayout)MainActivity.Activity.FindViewById(Resource.Id.navigationlayout_appbar))?.GetChildAt(0) as Toolbar;
        // Toolbar modifications
     }
}

Then, to change the appearance of the title view, you can get the titleview like so:

TextView titleView = null;
for (var i = 0; i < toolbar.ChildCount; i++)
    if ((titleView = toolbar.GetChildAt(i) as TextView) != null)
        break;

This worked for me, I had all the information, just didn't see the whole picture. Not what I needed, but it's working fine