好的...这是一种更长但有效的方法...
1) 在您的班级中创建一个全局变量,例如...
private boolean backPressedToExitOnce = false;
private Toast toast = null;
2)然后像这样实现activity的onBackPressed...
@Override
public void onBackPressed() {
if (backPressedToExitOnce) {
super.onBackPressed();
} else {
this.backPressedToExitOnce = true;
showToast("Press again to exit");
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
backPressedToExitOnce = false;
}
}, 2000);
}
}
3) 使用这个技巧来有效地处理这个吐司......
/**
* Created to make sure that you toast doesn't show miltiple times, if user pressed back
* button more than once.
* @param message Message to show on toast.
*/
private void showToast(String message) {
if (this.toast == null) {
// Create toast if found null, it would he the case of first call only
this.toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
} else if (this.toast.getView() == null) {
// Toast not showing, so create new one
this.toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
} else {
// Updating toast message is showing
this.toast.setText(message);
}
// Showing toast finally
this.toast.show();
}
4) 并在活动关闭时使用此技巧隐藏 toast...
/**
* Kill the toast if showing. Supposed to call from onPause() of activity.
* So that toast also get removed as activity goes to background, to improve
* better app experiance for user
*/
private void killToast() {
if (this.toast != null) {
this.toast.cancel();
}
}
5) 像这样实现 onPause(),当活动进入后台时立即杀死 toast
@Override
protected void onPause() {
killToast();
super.onPause();
}
希望这会有所帮助...:)