Xamarin.Forms安卓端重置NavigationRoot后OnOptionsItemSelected未触发
问题根因
你当前只在MainActivity的OnCreate生命周期方法中执行了一次Toolbar查找和SetSupportActionBar绑定操作。当你执行导航根重置操作时,Xamarin.Forms会重新渲染根页面布局,原有绑定的Toolbar实例会被销毁替换,原生层的ActionBar和新的Toolbar失去关联,因此OnOptionsItemSelected无法再被触发。
解决方案
你需要在每次页面导航根更新后,重新执行Toolbar的查找和绑定操作,具体修改如下:
- 把Toolbar绑定逻辑提取为公共方法
- 监听Xamarin.Forms的页面导航事件,在根页面变更时重新绑定Toolbar
- 替换硬编码的菜单ID为官方常量,避免兼容性问题
修改后的完整代码:
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App(new AndroidInitializer())); // 初始绑定Toolbar BindToolbar(); // 监听全局页面显示事件,根页面变更时重新绑定 Xamarin.Forms.Application.Current.PageAppearing += (s, e) => { // 仅根页面触发时执行绑定,避免不必要的重复操作 if (e.Page == Xamarin.Forms.Application.Current.MainPage) { RunOnUiThread(BindToolbar); } }; } private void BindToolbar() { Toolbar toolbar = this.FindViewById<Toolbar>(Resource.Id.toolbar); if (toolbar != null) { SetSupportActionBar(toolbar); // 确保返回按钮正常显示和响应 SupportActionBar.SetDisplayHomeAsUpEnabled(true); SupportActionBar.SetHomeButtonEnabled(true); } } public override bool OnOptionsItemSelected(IMenuItem item) { // 替换硬编码ID为官方常量,提升可读性和兼容性 if (item.ItemId == Android.Resource.Id.Home) { // 原有业务逻辑 return true; } return base.OnOptionsItemSelected(item); } }
补充校验点
如果修改后仍存在问题,可以检查导航根重置逻辑:重置Application.Current.MainPage时,确保新的根页面是搭载NavigationPage的实例,且NavigationPage的HasNavigationBar属性未被设置为false。
内容的提问来源于stack exchange,提问作者Michael de Vlieger
相关产品推荐
相关产品推荐

