1

I have one activity and five fragments.I have a navigation drawer button in option menu which helps me to navigate through fragment.But on one fragment i want to change that to back button.Currently back button is working correctly.But together with that the activity option menu also working and it will bring navigation drawer up.How to stop that?

Here is my drawer

MainActivity

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_settings:
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.container, new SettingsFragment());
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();
            break;       
        case android.R.id.home:
            mDrawerLayout.openDrawer(GravityCompat.START);
            break;
        default:
            break;
    }
    return super.onOptionsItemSelected(item);
}

Fragment

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            getFragmentManager().popBackStack();
            return true;
        default:
            break;
    }
    return super.onOptionsItemSelected(item);
}

Actually when i select option menu home code in both option menu is working i want only fragment option menu to work. how can i stop it?Please help

sachithkn
  • 457
  • 1
  • 4
  • 13

1 Answers1

1

First, in your activity, create a flag to check whether home button as back button or not: isBackShow = false. Then, in onOptionsItemSelected:

 case android.R.id.home: // show drawer or pop backstack base on flag
        if(isBackShow)
        getFragmentManager().popBackStack();
        mDrawerLayout.openDrawer(GravityCompat.START);
        return true;

In your SettingsFragment, you can change flag of father Activity as below in onCreateView or in somewhere you want:

if(getActivity() instanceof YourFatherActivity){
        ((YourFatherActivity)getActivity()).isBackShow = true;
        // You can also change drawer icon to back icon here.
}

I'm not check the code however, AFAIK this code will work. Hope this help.

Kingfisher Phuoc
  • 8,052
  • 9
  • 46
  • 86