我是 Xamarin.Forms 的新手。我试图在单击 NavigationBar 后退按钮 时显示 DisplayAlert()
。我已经尝试根据 this article 实现.问题是当我点击按钮时弹出窗口没有出现。我在 OnOptionsItemSelected()
方法上放置了一个断点,以查看它是否被调用,它没有。这是我的 MainActivity.cs
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
global::Xamarin.FormsMaps.Init(this, bundle);
LoadApplication(new App());
Android.Support.V7.Widget.Toolbar toolbar = this.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
//Placed a debugger here
// check if the current item id is equals to the back button id
if (item.ItemId == 16908332)
{
// retrieve the current xamarin forms page instance
var currentpage = Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack.LastOrDefault() as NavBackButtonContentPage;
// check if the page has subscribed to the custom back button event
if (currentpage?.CustomBackButtonAction != null)
{
// invoke the Custom back button action
currentpage?.CustomBackButtonAction.Invoke();
// and disable the default back button action
return false;
}
// if its not subscribed then go ahead with the default back button action
return base.OnOptionsItemSelected(item);
}
else
{
// since its not the back button click, pass the event to the base
return base.OnOptionsItemSelected(item);
}
}
我在 MasterDetailPage
中使用它。
最佳答案
isaman kumara 2019-06-01 的评论如下:
The issue will be fixed when you add following lines to MainActivity OnCreate method (after the LoadApplication(new App()); line)
Android.Support.V7.Widget.Toolbar toolbar = this.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar); SetSupportActionBar(toolbar);
其中一个回复是这样说的:
This seems to no longer be working. SetSupportActionBar expects a parameter of type AndroidX.AppCompat.Widget.Toolbar and it won't work with Android.Support.V7.Widget.Toolbar.
通过在 LoadApplication 行之后将此添加到 MainActivity 的 OnCreate 方法,我能够让 OnOptionsItemSelected 在 Xamarin Forms 4.8 中再次工作:
if (FindViewById(Resource.Id.toolbar) is AndroidX.AppCompat.Widget.Toolbar toolbar)
{
SetSupportActionBar(toolbar);
}
很抱歉没有直接评论之前的评论,但我没有足够的声望点数来这样做。
关于android - Xamarin.Forms 中未调用 OnOptionsItemSelected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50676509/