Nancy
Nancy

Reputation: 1051

onBackPressed fragment goes to another fragment instead on closing the app

I'm opening a fragment through another fragment. From a calendar fragment I open a search fragment, I would like that when the person is in the search fragment and presses back it takes them to the calendar fragment instead of closing the app.

In my MainActivity.java I implemented the onBackPressed method

@Override
public void onBackPressed() {
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

This is how I'm opening up the fragments in the MainActivity.java

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
        case R.id.nav_calendar:
           getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new CalendarFragment()).commit();
            break;
        case R.id.nav_survey:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new SurveyFragment()).commit();
            break;
        case R.id.nav_forum:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ForumFragment()).commit();
            break;
        case R.id.nav_logout:
            logout();
            break;
        case R.id.nav_contact:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ContactFragment()).commit();
            break;
    }

    drawer.closeDrawer(GravityCompat.START);
    return true;
}

This is how I open the search fragment from the calendar fragment

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.search:
            getFragmentManager().beginTransaction().replace(R.id.fragment_container, new SearchFragment()).commit();
            return false;
        default:
            break;
    }
    return super.onOptionsItemSelected(item);
}

Is there a way to change the behavior on that fragment only and keep the normal behavior on the rest?

Upvotes: 0

Views: 36

Answers (1)

Jaimil Patel
Jaimil Patel

Reputation: 1347

When you write code in Calender Fragment to open Search Fragment at that time please add below line into FragmentTransaction operation like...

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.search:
            getFragmentManager().beginTransaction().add(R.id.fragment_container, new SearchFragment()).addToBackStack(null).commit();
            return false;
        default:
            break;
    }
    return super.onOptionsItemSelected(item);
}

Upvotes: 1

Related Questions