简体   繁体   English

onbackpress转到主屏幕,而不是先前的活动

[英]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. 从家里开始其他活动时,请不要使用finish()方法。

//remove the finish method from the home screen. //从主屏幕删除finish方法。

Firstly, please read and understand my answer here to clear your MainActivity 's backstacks. 首先,请阅读并理解我的回答以清除MainActivity的后备堆栈。 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 ). 因此,除非您先返回主屏幕并关闭主屏幕的“ Activity ,否则您将无法直接关闭应用程序(请参阅此问题 )。

CurrentActivity : 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. 注意:onResume()方法中调用finish()可能会导致问题。

Call finish() in the onResume() method inside your HomeScreenActivity : HomeScreenActivity内部的onResume()方法中调用finish()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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