Saidur Rahman Saidur Rahman - 3 months ago 35
Android Question

Handling back key for navigation drawer and fragment page

I am working on a app where I have few fragment pages also I have navigation drawer menu.

When I am on any fragments page and click on back key, application exit dialog is working fine. But when I am on any fragment page and at the same time if I click navigation menu, navigation menu is top position. Now if I click on back key, application exit button is coming but I want navigation menu should disappear first not the exit dialogue box.

Code for 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);
}

Answer
 @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();
    }
}