单击两次后退按钮退出活动 [英] Clicking the back button twice to exit an activity
问题描述
我最近在很多 Android 应用和游戏中都注意到了这种模式:当点击后退按钮退出"应用时,Toast
会出现类似于请点击再次返回退出".
我想知道,随着我越来越频繁地看到它,这是您可以在活动中以某种方式访问的内置功能吗?我查看了许多类的源代码,但似乎找不到任何相关内容.
当然,我可以考虑几种很容易实现相同功能的方法(最简单的方法可能是在 Activity 中保留一个布尔值来指示用户是否已经点击过一次...)但我想知道是否有东西已经在这里了.
编辑:正如@LAS_VEGAS 所提到的,我的意思并不是传统意义上的退出".(即终止)我的意思是回到应用程序启动活动启动之前打开的任何内容",如果这是有道理的:)
在 Java 活动中:
boolean doubleBackToExitPressedOnce = false;@覆盖公共无效 onBackPressed() {如果(doubleBackToExitPressedOnce){super.onBackPressed();返回;}this.doubleBackToExitPressedOnce = true;Toast.makeText(this, "请再次单击返回退出", Toast.LENGTH_SHORT).show();新处理程序(Looper.getMainLooper()).postDelayed(new Runnable() {@覆盖公共无效运行(){doubleBackToExitPressedOnce=false;}}, 2000);}
<块引用>
在 Kotlin 活动中:
private var doubleBackToExitPressedOnce = false覆盖乐趣 onBackPressed() {如果(doubleBackToExitPressedOnce){super.onBackPressed()返回}this.doubleBackToExitPressedOnce = trueToast.makeText(this, "请再次单击返回退出", Toast.LENGTH_SHORT).show()处理程序(Looper.getMainLooper()).postDelayed(Runnable { doubleBackToExitPressedOnce = false }, 2000)}
我认为这个处理程序有助于在 2 秒后重置变量.
I've noticed this pattern in a lot of Android apps and games recently: when clicking the back button to "exit" the application, a Toast
comes up with a message similar to "Please click BACK again to exit".
I was wondering, as I'm seeing it more and more often, is that a built-in feature that you can somehow access in an activity? I've looked at the source code of many classes but I can't seem to find anything about that.
Of course, I can think about a few ways to achieve the same functionality quite easily (the easiest is probably to keep a boolean in the activity that indicates whether the user already clicked once...) but I was wondering if there's something already here.
EDIT: As @LAS_VEGAS mentioned, I didn't really mean "exit" in the traditional meaning. (i.e. terminated) I meant "going back to whatever was open before the application start activity was launched", if that makes sense :)
In Java Activity:
boolean doubleBackToExitPressedOnce = false;
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
In Kotlin Activity:
private var doubleBackToExitPressedOnce = false
override fun onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed()
return
}
this.doubleBackToExitPressedOnce = true
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show()
Handler(Looper.getMainLooper()).postDelayed(Runnable { doubleBackToExitPressedOnce = false }, 2000)
}
I Think this handler helps to reset the variable after 2 second.
这篇关于单击两次后退按钮退出活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!