简体   繁体   中英

onbackpress go to home screen instead of previous activity

i have a navigation drawer which should close on backpress this works perfectly but when the navigation drawer closes and there is a second time back button press the app closes instead of going to home screen

here is the code i am trying

@Override
    public void onBackPressed() {
        // TODO Auto-generated method stub

        if(drawerLayout.isDrawerOpen(Gravity.LEFT)){
            drawerLayout.closeDrawer(Gravity.LEFT);
        }else{
            //super.onBackPressed();
             Intent mainActivity = new Intent(Intent.ACTION_MAIN);
             mainActivity.addCategory(Intent.CATEGORY_HOME);
             mainActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
             startActivity(mainActivity);

        }

how can we close the navigation drawer then go directly to home screen/ main activity

i donot wan to use

Intent i = new Intent(AccountActivity.this, HomeActivity.class);
                    startActivity(i);

While starting the another activity from the home dont use the finish() method.

//remove the finish method from the home screen.

Firstly, please read and understand my answer here to clear your MainActivity 's backstacks. My method will not work until you understand that.

So you cannot to close your app directly, unless you back to home screen first and close the home screen's Activity (see this question ).

CurrentActivity :

if(drawerLayout.isDrawerOpen(Gravity.LEFT)) {
    drawerLayout.closeDrawer(Gravity.LEFT);
}else{
// After you understood my answer above (I link it with "here"),
// you just need this call:
    startActivity(new Intent(CurrentActivity.this, HomeScreenActivity.class));
}

Notice: Calling finish() in the onResume() method might cause a problem.

Call finish() in the onResume() method inside your HomeScreenActivity :

@Override
protected void onResume() {
    super.onResume();
    HomeScreenActivity.this.finish();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM