user5661075
user5661075

Reputation:

Show alert on press back button

I writing android app on Xamarin(C#)

I need to Show alert with "Yes" and "No" variantes when I tap back button on Activity.

How can I realize this?

I know how to show alert. How I can make it when i press back button

Upvotes: 1

Views: 1200

Answers (3)

luckyShubhra
luckyShubhra

Reputation: 2751

Since Xamarin Forms 1.3.0 pre3, there is a new method:

protected bool OnBackButtonPressed();

You need to override this on your page.

    protected override bool OnBackButtonPressed()
    {    
         // If you want to stop the back button and show alert
         return true;

         // If you want to continue going back
          base.OnBackButtonPressed();
          return false; 
    }

Thanks to Xamarin Forums. Refer this link for more info.

Upvotes: 0

Thomas Hilbert
Thomas Hilbert

Reputation: 3629

Xamarin provides wrappers to the native Android Activity classes. So you probably have a MainActivity and maybe other Activity classes in your Xamarin Android project. In these classes you can override the OnBackPressed method inherited from FormsApplicationActivity and then create and show your Alert from there.

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
    public override void OnBackPressed()
    {
        // show Alert or pass call on to base.OnBackPressed()
    }
}

Upvotes: 1

Amit Vaghela
Amit Vaghela

Reputation: 22945

try this , add to your activity

@Override
    public void onBackPressed() {
        AlertDialog.Builder builder =
                    new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
            builder.setTitle(getResources().getString(R.string.app_name));
            builder.setMessage("" + Message);
            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    //write your code

                }
            });
            builder.setNegativeButton("No", null);
            builder.setCancelable(false);
            builder.show();
    }

Upvotes: 2

Related Questions