Why I need to press back button twice to dismiss fragment on first time?

878 views Asked by At

I have Base Activity including NavigationView with 2 menu items. On start it loads Home fragment having background image inside it. Each loads specific fragment. When I select Terms & Conditions menu item, it loads T&C fragment & when I press back button it simply kills it.

However, when I select About Us menu item, it loads About Us fragment but I need to press BACK button twice to kill it. I need to know why does it happen?

Part of Code in AppBaseActivity

@Override
    protected void onCreate(Bundle savedInstanceState) {
        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        HomeFragment homeFragment = new HomeFragment();
        fragmentTransaction.add(R.id.body_container, homeFragment, "");
        fragmentTransaction.commit();
}

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        navigationView.getMenu().findItem(item.getItemId()).setChecked(true);
switch (item.getItemId()) {
            case R.id.nav_terms :
                fragmentTransaction = fragmentManager.beginTransaction();
                TCFragment tcFragment = new TCFragment();
                fragmentTransaction.replace(R.id.body_container, tcFragment, "");
                fragmentTransaction.commit();
                break;

            case R.id.nav_about_us :
                fragmentTransaction = fragmentManager.beginTransaction();
                AboutUsFragment aboutUsFragment = new AboutUsFragment();
                fragmentTransaction.replace(R.id.body_container, aboutUsFragment, "");
                fragmentTransaction.commit();
                break;
}

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
}

All fragments simply have overridden onCreateView() by inflating respected xml only. No code is written in both fragments yet.

2

There are 2 answers

1
santosh kumar On
@Override
    public void onBackPressed() {
    super.onBackPressed();    
}
0
Kishore Jethava On

You can stop back hardware navigation if you want.

Simply using onBackPressed() without super.onBackPressed()

@Override
public void onBackPressed() {

}