Skip to content Skip to sidebar Skip to footer

Changing The Actionbar Menu State Depending On Fragment

I am trying to show/hide items in my action bar depending on which fragment is visible. In my MainActivity I have the following /* Called whenever invalidateOptionsMenu() is call

Solution 1:

Based on the Fragments API Guide, we can add items to the action bar on a per-Fragment basis with the following steps: Create a res/menu/fooFragmentMenu.xml that contains menu items as you normally would for the standard menu.

<menuxmlns:android="http://schemas.android.com/apk/res/android" ><itemandroid:id="@+id/newAction"android:orderInCategory="1"android:showAsAction="always"android:title="@string/newActionTitle"android:icon="@drawable/newActionIcon"/></menu>

Toward the top of FooFragment's onCreate method, indicate that it has its own menu items to add.

@OverridepublicvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    ...
}

Override onCreateOptionsMenu, where you'll inflate the fragment's menu and attach it to your standard menu.

@OverridepublicvoidonCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.fooFragmentMenu, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

Override onOptionItemSelected in your fragment, which only gets called when this same method of the host Activity/FragmentActivity sees that it doesn't have a case for the selection.

@OverridepublicbooleanonOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.newAction:
            ...
            break;
    }
    returnsuper.onOptionsItemSelected(item);
}

Solution 2:

Try using Fragment's setRetainInstance(true); when your fragment is attached to the Activity. That way your fragment will retain it's current values and call the lifecycle when device rotated.

Solution 3:

Edit: This is a quick and dirty fix, see es0329's answer below for a better solution.

Try adding this attribute to your activity tag in your android manifest:

android:configChanges="orientation|screenSize"

Post a Comment for "Changing The Actionbar Menu State Depending On Fragment"