在mainActivity中未调用OnOptionsItemSelected方法

时间:2018-04-11 17:45:34

标签: android xamarin xamarin.forms

OnOptionsItemSelected()方法永远不会被调用,如果它是Masterdetail页面。如果是常规导航页面,则可以使用。

1 个答案:

答案 0 :(得分:0)

看了Xamarin.Forms来源似乎我找到了解决方案。 您必须为NavigationPage创建渲染器并覆盖OnAttachedToWindow

    protected override void OnAttachedToWindow()
    {
        base.OnAttachedToWindow();

        Element page = Element.Parent;
        MasterDetailPage masterDetailPage = null;
        while (page != null)
        {
            if (page is MasterDetailPage)
            {
                masterDetailPage = page as MasterDetailPage;
                break;
            }

            page = page.Parent;
        }

        if (masterDetailPage == null)
        {
            return;
        }

        var renderer = Platform.GetRenderer(masterDetailPage) as MasterDetailPageRenderer;
        if (renderer == null)
        {
            return;
        }

        var drawerLayout = (DrawerLayout) renderer;
        Toolbar toolbar = null;

        for (int i = 0; i < ChildCount; i++)
        {
            var child = GetChildAt(i);
            toolbar = child as Toolbar;
            if (toolbar != null)
            {
                break;
            }
        }

        toolbar?.SetNavigationOnClickListener(new MenuClickListener(Element, drawerLayout));
    }

    private class MenuClickListener : Java.Lang.Object, IOnClickListener
    {
        readonly NavigationPage navigationPage;
        private DrawerLayout layout;

        public MenuClickListener(NavigationPage navigationPage, DrawerLayout layout)
        {
            this.navigationPage = navigationPage;
            this.layout = layout;
        }

        public void OnClick(View v)
        {
            var page = navigationPage.CurrentPage as BasePage;
            if (navigationPage.Navigation.NavigationStack.Count <= 1)
            {
                layout.OpenDrawer((int) GravityFlags.Left);
            }

            if (page != null)
            {
                if (page.OnNavigationBackButtonPressed())
                {
                    navigationPage?.PopAsync();
                }
            }
            else
            {
                navigationPage?.PopAsync();
            }
        }
    }

BasePage - 来自ContentPage,并且方法OnNavigationBackButtonPressed可以处理特殊逻辑。

点击此处查看更多信息https://forums.xamarin.com/discussion/87795/onoptionsitemselected-not-invoked-using-masterdetails-page-on-android