How to go back to previous fragment from activity?

前端 未结 8 1386
太阳男子
太阳男子 2021-02-07 08:26

I\'ve got an app with nav drawer, which is switching fragments. From inside one of those fragments, I am calling a new activity. When I click back in this activity (in toolbar),

相关标签:
8条回答
  • 2021-02-07 09:04

    I see, that people are still trying to help me. This answer helped me fix my problem: Android - Navigation Up from Activity to Fragment

    0 讨论(0)
  • 2021-02-07 09:06

    What I tend to do is this

    @Override
    public void onBackPressed() {
        if (getFragmentManager().getBackStackEntryCount() == 0) {
            this.finish();
        } else {
            super.onBackPressed(); //replaced
        }
    }
    

    This way it handles the fragment stuff on its own within, but when there's no fragments left to go back to, then it finishes the activity.

    EDIT: UP navigation can recreate your previous activity even if it already exists. To prevent that from happening, redefine the Up navigation's event in onOptionsItemSelected like so:

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                Intent parentIntent = NavUtils.getParentActivityIntent(this);
                if(parentIntent == null) { 
                    finish();
                    return true;
                } else {
                    parentIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                    startActivity(parentIntent);
                    finish();
                    return true;
                }
        }
        return super.onOptionsItemSelected(item);
    }
    
    0 讨论(0)
提交回复
热议问题