2

I am following these tutorials to implement Searchbar in NavigationPage in Xamarin.Forms:

I have a simple ContentPage which I open in App.cs In NavigationPage form:

var navigationPage = new Xamarin.Forms.NavigationPage(new Home());
navigationPage.On<iOS>().SetPrefersLargeTitles(true);
MainPage = navigationPage;

While running the project I get error in Renderer Page in the following line:

Toolbar GetToolbar() => CrossCurrentActivity.Current.Activity.FindViewById<Toolbar>(Resource.Id.toolbar);

the exception thrown is:

System.InvalidCastException: 'Unable to convert instance of type 'Android.Support.V7.Widget.Toolbar' to type 'Android.Widget.Toolbar'.'

I can't figure out why this error appears, although it shows that it has problem in casting.

Does anyone see where is my error?

deczaloth
  • 7,094
  • 4
  • 24
  • 59
ARH
  • 1,566
  • 3
  • 25
  • 56

1 Answers1

2

Solution

Change your line with error to

var toolbar = CrossCurrentActivity.Current.Activity.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);

Explanation

Even though it is not clear with the piece of code you shared, it seems that your Renderer Class is using Android.Widget, which also defines a Toolbar member and might be conflicting with the return value of FindViewById which is Android.Support.V7.Widget.Toolbar.

So, now that the fix is explained, i would add that a better way to fix your problem is either removing the using Android.Widget and add instead using Android.Support.V7.Widget.Toolbar so you can write code like

using Android.Support.V7.Widget;
...

// This Toolbar refers to the one in V7!
Toolbar toolbar = CrossCurrentActivity.Current.Activity.FindViewById<Toolbar>(Resource.Id.toolbar);

or if you still need using Android.Widget, then you could use an alias:

using Android.Widget;
using V7Toolbar = Android.Support.V7.Widget.Toolbar;
...

// This Toolbar refers to the one in V7!
V7Toolbar toolbar = CrossCurrentActivity.Current.Activity.FindViewById<V7Toolbar>(Resource.Id.toolbar);
deczaloth
  • 7,094
  • 4
  • 24
  • 59