简体   繁体   English

按下后退按钮显示警报

[英]Show alert on press back button

I writing android app on Xamarin(C#) 我在Xamarin上编写Android应用程序(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 当我按下后退按钮时,我怎么能做到

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();
    }

Xamarin provides wrappers to the native Android Activity classes. Xamarin为本机Android Activity类提供包装器。 So you probably have a MainActivity and maybe other Activity classes in your Xamarin Android project. 所以你可能在你的Xamarin Android项目中有一个MainActivity和其他Activity类。 In these classes you can override the OnBackPressed method inherited from FormsApplicationActivity and then create and show your Alert from there. 在这些类中,您可以覆盖从FormsApplicationActivity继承的OnBackPressed方法,然后从那里创建并显示警报。

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

Since Xamarin Forms 1.3.0 pre3, there is a new method: 由于Xamarin Forms 1.3.0 pre3,有一种新方法:

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. 感谢Xamarin论坛。 Refer this link for more info. 有关详细信息,请参阅链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM