Android:在Toast上使用onBackPressed()的正确方法 [英] Android: Proper Way to use onBackPressed() with Toast
本文介绍了Android:在Toast上使用onBackPressed()的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一段代码,将提示用户是否要退出,请他们再按一次.目前,我的代码在一定程度上可以正常工作,但是我知道代码编写得很差,并且我认为有更好的方法可以做到这一点.任何建议都会有所帮助!
I wrote a piece of code that will give the user a prompt asking them to press back again if they would like to exit. I currently have my code working to an extent but I know it is written poorly and I assume there is a better way to do it. Any suggestions would be helpful!
代码:
public void onBackPressed(){
backpress = (backpress + 1);
Toast.makeText(getApplicationContext(), " Press Back again to Exit ", Toast.LENGTH_SHORT).show();
if (backpress>1) {
this.finish();
}
}
推荐答案
我将实现一个对话框,询问用户是否要退出,然后调用super.onBackPressed()
.
I would implement a dialog asking the user if they wanted to exit and then call super.onBackPressed()
if they did.
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Really Exit?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
WelcomeActivity.super.onBackPressed();
}
}).create().show();
}
在上面的示例中,您需要用活动名称替换WelcomeActivity.
In the above example, you'll need to replace WelcomeActivity with the name of your activity.
这篇关于Android:在Toast上使用onBackPressed()的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文