試試這個,如果你使用的是碎片android.support.v4.app.Fragment。
private boolean allowExit = false;
然後
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
// handling fragment backbutton navigation
getSupportFragmentManager().popBackStack();
} else {
if (allowExit) {
super.onBackPressed();
} else {
Toast.makeText(this, getString(R.string.app_exit_message), Toast.LENGTH_SHORT).show();
allowExit = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
allowExit = false;
}
}, 3000);
}
}
}
如果使用不支持分片必須更換
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else if (getFragmentManager().getBackStackEntryCount() > 0) {
// handling fragment backbutton navigation
getFragmentManager().popBackStack();
} else {
if (allowExit) {
super.onBackPressed();
} else {
Toast.makeText(this, getString(R.string.app_exit_message), Toast.LENGTH_SHORT).show();
allowExit = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
allowExit = false;
}
}, 3000);
}
}
}
並添加消息到string.xml
<string name="app_exit_message">Press again to exit</string>
添加片段以通過重新加載片段來手動堆疊或管理它 –