当后退按钮点击两次时如何让Xamarin.Android app退出(确认包含点击之间的消息)()

知识就是力量,时间就是生命。这篇文章主要讲述当后退按钮点击两次时如何让Xamarin.Android app退出(确认包含点击之间的消息)?相关的知识,希望能为你提供帮助。
在我的MainActivity中,我像那样覆盖了OnBackPressed()方法

public override void OnBackPressed() { Toast toast = Toast.MakeText(this, "Press again to exit", ToastLength.Short); toast.SetMargin(0,0.20f); toast.Show(); }

当用户处于MainActivity并单击后退按钮一次时,屏幕上会显示消息“再按一次退出”,此消息在几秒钟后消失。如果用户在屏幕上显示此消息时再次单击后退按钮,我希望应用程序退出,但当消息消失且用户单击后退按钮时,我希望消息再次出现。我在java中看到过一些这样的例子,但是我发现很难让这些例子适用于Xamarin.android。
答案这段代码工作正常。
long lastPress; public override void OnBackPressed() { // source https://stackoverflow.com/a/27124904/3814729 long currentTime = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond; // source https://stackoverflow.com/a/14006485/3814729 if (currentTime - lastPress > 5000) { Toast.MakeText(this, "Press back again to exit", ToastLength.Long).Show(); lastPress = currentTime; } else { base.OnBackPressed(); } }

如果您想使用短吐司长度,请更改时间。
ToastLength.Long = 3500(ms)
ToastLength.Short = 2000(ms)
另一答案
Toast toast = Toast.MakeText(Application.Context, "Press again to exit", ToastLength.Short); bool doubleBackToExitPressedOnce = false; public override void OnBackPressed() { if (doubleBackToExitPressedOnce) { toast.Cancel(); base.OnBackPressed(); return; }toast.SetMargin(0, 0.20f); toast.Show(); this.doubleBackToExitPressedOnce = true; new Handler().PostDelayed(() => { doubleBackToExitPressedOnce = false; }, 2000); }

另一答案【当后退按钮点击两次时如何让Xamarin.Android app退出(确认包含点击之间的消息)()】我建议的最可靠的方法是这样的:
public static bool doubleBackToExitPressedOnce=truepublic override void OnBackPressed() { if (doubleBackToExitPressedOnce) { FinishAffinity(); } Common.FragmentManager.doubleBackToExitPressedOnce = true; Toast.MakeText(this, Resources.GetString(Resource.String.back_click_on_home), ToastLength.Short).Show(); new Handler().PostDelayed(new RunnableHelper(), 2000); } public class RunnableHelper : Java.Lang.Object, IRunnable { public void Run() { doubleBackToExitPressedOnce = false; } }


    推荐阅读