0

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

  • In the line you declare actionBar is the 'Context' you use Xamarin.Forms.Forms.Context? – cvanbeek Nov 28 '17 at 17:03
  • no it's Android.Content.Context. I also tried Forms but still returns null – Stamatis Stiliats Nov 29 '17 at 07:40
  • That's your issue. That context isn't an actual activity in your app, so it has no action bar. You need to use the current activity of your app like Wilson Vargas does in his answer. – cvanbeek Nov 29 '17 at 12:20

1 Answers1

3

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

Wilson Vargas
  • 2,841
  • 1
  • 19
  • 28