Home > OS >  AndroidX.AppCompat.Widget.Toolbar always null
AndroidX.AppCompat.Widget.Toolbar always null

Time:12-30

I'm applying custom solution to override back click of the navigation bar. but, the toolbar object always null and crashes the app.

MainActivity class

     protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;
             
            base.OnCreate(savedInstanceState);
            ZXing.Mobile.MobileBarcodeScanner.Initialize(Application); 
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
           
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

            LoadApplication(new App());
             //always null
            AndroidX.AppCompat.Widget.Toolbar toolbar
            = this.FindViewById<AndroidX.AppCompat.Widget.Toolbar>(Resource.Id.toolbar);
            //null exception
            SetSupportActionBar(toolbar);
        }

toolbar.xml

<androidx.appcompat.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@ id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#00748a"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    android:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

Is there any solution?

CodePudding user response:

You can try to change the layout name toolbar.xml to Toolbar.xml.

Besides, since you have used following code:

  TabLayoutResource = Resource.Layout.Tabbar;

You also need to add layout Tabbar.xml in folder layout of android platform. In my code, I didn't add TabLayoutResource = Resource.Layout.Tabbar;

And you can get the sample here,which works on my side.

CodePudding user response:

At App.cs, I replaced this line of code

    MainPage =  new Login();

with this line, so the toolbar get initialized

    MainPage = new Xamarin.Forms.NavigationPage(new Login());
  • Related