Search code examples
c#xamarin.formscustom-renderer

NavigationPage rendere for android. Xamarin Forms


I am trying to access the actionbar from a custom renderer(i know i can use the toolbar.xml but it's not fitting my situation). Here is my code

[assembly: ExportRenderer(typeof(NavigationPage), typeof(NoviNavigationPageRenderer))]
namespace NoviMobileTest.Droid.Renderers
{
    public class NoviNavigationPageRenderer : PageRenderer
    {

        protected override void OnLayout(bool changed, int l, int t, int r, int b)
        {
                base.OnLayout(changed, l, t, r, b);
                var actionBar = ((Activity)Context).ActionBar;
                actionBar.SetBackgroundDrawable(Resources.GetDrawable(Resource.Drawable.YourImageInDrawable));
        }
    }
}

variable actionbar is always null. I also tried extending NavigationRenderer but i get class cast exception. I've seen many people having the same issue but it's amazing that there are no examples out there to see. How am i suppose to get instance of the toolbar?

NOTE: my MainActivity extends FormsAppCompatActivity

Thanks in advance


Solution

  • Try installing CurrentActivity Plugin in your Android project and then like this:

    using Plugin.CurrentActivity;
    ...
    private static Android.Support.V7.Widget.Toolbar GetToolbar() => (CrossCurrentActivity.Current?.Activity as MainActivity)?.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
    

    Finally:

    protected override void OnLayout(bool changed, int l, int t, int r, int b)
        {
                base.OnLayout(changed, l, t, r, b);
                var actionBar = GetToolbar();
                actionBar.SetBackgroundDrawable(Resources.GetDrawable(Resource.Drawable.YourImageInDrawable));
        }
    

    For more information about this see: IconNavigationPageRenderer.cs