我希望用户确认关闭我的应用程序。我在MainActivity中使用了以下代码:
@Override
public void onBackPressed() {
if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
toast = Toast.makeText(this, "Press back again to close this app", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
this.lastBackPressTime = System.currentTimeMillis();
} else {
if (toast != null) {
toast.cancel();
}
super.onBackPressed();
}
}
在其他类中,我使用这个:
@Override public void onBackPressed() {
if (!mWebView.onBackPressed()) { return; }
// ...
super.onBackPressed(); }
现在我在每个类中都得到了确认事件,但我只想在我的MainActivity中得到它。我该怎么做?
注意:我必须在其他课程中扩展我的MainActivity。这应该是要解决的主要问题,但我仍然不知道具体如何解决?
@Vala,如果您将片段添加到Activty
,那么您可以使用FragmentManager
的BackSackEntryCount
,如下所示。
int backStackCount = getSupportFragmentManager().getBackStackEntryCount();
if (backStackCount == 1) {
Toast.makeText(this, "Press back again to close this app", Toast.LENGTH_LONG).show();
}
如果backstackcount
为一,则意味着再次按下后退按钮时,剩余的frgament将从后堆栈中弹出,应用程序将退出。
尝试使用在您的主要活动中
private boolean exit = false;
@Override
public void onBackPressed()
{
if (exit) {
finish(); // finish activity
} else {
Toast.makeText(this, "Press Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}
像这样尝试
Activity activity = this;
if (activity instanceof MainActivity) {
if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
Toast toast = Toast.makeText(this, "Press back again to close this app", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
this.lastBackPressTime = System.currentTimeMillis();
} else {
if (toast != null) {
toast.cancel();
}
super.onBackPressed();
}
} else {
super.onBackPressed();
}
将其他类更改为
@Override
public void onBackPressed() {
if (mWebView.canGoBack()) { return; }
// ...
super.onBackPressed();
}