XamarinForms AppCompat OnOptionsItemSelected

荒凉一梦 提交于 2019-12-10 18:45:25

问题


I have recently updated xamarin forms to 1.5.1-pre1 so that I can use the beautiful AppCompat themes. It works and looks very nice.

I do have one problem, in my old FormsApplicationActivity I used to override the OnOptionsItemSelected method to intercept when the user was clicking on the back arrow icon and do some viewmodel cleanup. Apparently this method is not being called after using the FormsAppCompatActivity. How can I intercept the "soft" back button press (toolbar icon not hard back button) ?

I also tried to override the Xamarin.Forms.Platform.Android.AppCompat.NavigationPageRenderer but i can't seem to override it :(

Does anyone have a clue how I can intercept this?


回答1:


Have a look at the last two lines of the OnCreate() After adding them OnOptionsItemSelected was called as expected).

https://raw.githubusercontent.com/UdaraAlwis/Xamarin-Playground/master/XFNavBarBackBtnClickOverride/XFNavBarBackBtnClickOverride/XFNavBarBackBtnClickOverride.Droid/MainActivity.cs

        Toolbar toolbar = this.FindViewById<Toolbar>(Resource.Id.toolbar);

        SetSupportActionBar(toolbar);



回答2:


You can add the following to your custom renderer. You can either user current activity plugin or cast your context to activity.

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

toolbar.NavigationClick += ToolbarNavigationClick;



回答3:


In Xamarin.Forms there's a better way to intercept the NavigationBar back button pressed and the hardware back button pressed, which is creating your own NavigationRenderer and overriding the method OnPopViewAsync:

[assembly: ExportRenderer(typeof(NavigationPage), typeof(CustomNavigationRenderer))]
namespace YourApp.Droid
{
    public class CustomNavigationRenderer : NavigationPageRenderer
    {
        public CustomNavigationRenderer(Context context) : base(context)
        {
        }

        protected override async Task<bool> OnPopViewAsync(Page page, bool animated)
        {
            // Write your code here
        }
    }
}

Hope this helps



来源:https://stackoverflow.com/questions/33078590/xamarinforms-appcompat-onoptionsitemselected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!