我正在开发一个应用程序,其中我有几个片段页面,我也有导航抽屉菜单。
当我在任何片段页面上并单击后退键时,应用程序退出对话框正常工作。但是当我在任何片段页面上,同时如果单击导航菜单,导航菜单就是最高位置。现在,如果我点击后退键,应用程序退出按钮即将到来但我希望导航菜单首先消失而不是退出对话框。
onBackPressed()的代码:
public void onBackPressed()
{
final FragmentManager fm = getSupportFragmentManager();
if(fm.getBackStackEntryCount() != 1){
super.onBackPressed();
}
else
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Exit Application?");
alertDialogBuilder
.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
=============================================== ===========================
Code for onDrawerItemClick():
private void onDrawerItemClick(final int item) {
UserService userService = new UserService(this);
switch (item) {
case TEST1:
test1();
break;
case TEST2:
test2();
break;
case LOGOUT:
userService.logout();
finish();
Toast.makeText(MenuActivity.this, "LOGOUT", Toast.LENGTH_SHORT).show();
break;
}
mDrawerLayout.closeDrawer(GravityCompat.START);
}
答案 0 :(得分:0)
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawerlayout);
assert drawer != null;
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
答案 1 :(得分:0)
在onBackPressed()
首先,您必须检查抽屉是否打开,如果它是打开关闭,否则执行正常操作。
在你的情况下:
public void onBackPressed()
{
final FragmentManager fm = getSupportFragmentManager();
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
} else if(fm.getBackStackEntryCount() != 1){
super.onBackPressed();
}
else
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Exit Application?");
alertDialogBuilder
.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
答案 2 :(得分:0)
这很容易。让我告诉你我的想法:
public void onBackPressed()
{
//The first line, you should check your drawer status.
if(drawerIsOpen){
closeDrawer();
}
else{
//show your exit dialog.
}
}