Confirmation Dialog on back button press event Xamarin.Forms

后端 未结 6 817
北海茫月
北海茫月 2020-12-14 19:16

I am stuck at one point in Xamarin.Forms application

On Back button press simply I want to ask user to confirm whether he really wants to exit or not, \"OnBackButton

6条回答
  •  春和景丽
    2020-12-14 19:51

    If you are on Mainpage and want to exit your app then this code will help you.

    In your UI (PCL)

      protected override bool OnBackButtonPressed()
                {
    
                    Device.BeginInvokeOnMainThread(new Action(async () => {
                        var result = await this.DisplayAlert("Alert!", "Do you really want to exit?", "Yes", "No");
    
                        if (result)
                        {
                            if (Device.RuntimePlatform == Device.Android)
                                DependencyService.Get().CloseApp();
                        }
                    }));
                    return true;
                }
    

    Also create an Interface (in your UI PCL):

    public interface IAndroidMethods
    {
        void CloseApp();
    }
    

    Now implement the Android-specific logic in your Android project:

    [assembly: Xamarin.Forms.Dependency(typeof(AndroidMethods))]
    namespace Your.Namespace
    {
       public class AndroidMethods : IAndroidMethods
       {
           public void CloseApp()
           {
                 var activity = (Activity)Forms.Context;
                activity.FinishAffinity();
           }
       }
    }
    

提交回复
热议问题