Reputation: 493
I have a 3 page Fragment in my app, but I need each fragment to have a different ActionBar. For one fragment I have set the current code in the OnCreateView
method that adds in an EditText
to the ActionBar:
//mainActivityContext is the context for the Main Activity (This is a fragment file)
ActionBar actionBar = mainActivityContext.getActionBar();
// add the custom view to the action bar
actionBar.setCustomView(R.layout.actionbar_view);
search = (EditText) actionBar.getCustomView().findViewById(R.id.searchfield);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
| ActionBar.DISPLAY_SHOW_HOME);
Yet this EditText
stays persistent throughout all of the ActionBar menus. I only want it on one. I have tried everything, menu.clear();
, setHasOptionsMenu(true);
, inflater.inflate(R.menu.different_file, menu);
, but nothing has worked.
Any help?
Upvotes: 0
Views: 2052
Reputation: 6736
There is a very good approach to go about this situation:
on each fragment's onActivityCreated()
method call setHasOptionsMenu(true);
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
now you can override onCreateOptionsMenu()
and onOptionsItemSelected()
inside each fragment.
And also dont forget to call getActivity().supportInvalidateOptionsMenu();
inside onResume()
of fragment.
I think this sample by google will be very helpful.
Upvotes: 1
Reputation: 691
Since the actions are populated by the activity's options menu you can use Activity#invalidateOptionsMenu()
. This will dump the current menu and call your activity's onCreateOptionsMenu/onPrepareOptionsMenu
methods again to rebuild it.
If you're using action bar tabs to change your fragment configuration there's a better way. Have each fragment manage its own portion of the menu. These fragments should call setHasOptionsMenu(true). When fragments that have options menu items are added or removed the system will automatically invalidate the options menu and call to each fragment's onCreateOptionsMenu/onPrepareOptionsMenu methods in addition to the activity's. This way each fragment can manage its own items and you don't need to worry about performing menu switching by hand.
Upvotes: 0