Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Menu Ordering differences due to Fragment and Activity hierarchy. (onCreateOptionsMenu)

Background

Developing for Android 3.0, I have a HostActivity that is the superclass of NotebooksActivity and NoteActivity. NotebooksActivity includes a fragment, NotebooksFragment.

In HostActivity, I include a menu that I want to appear at the rightmost end of the options menu in the ActionBar, i.e. all menu items in subclasses of HostActivity should appear to the left of the menu items added in HostActivity.

Menu inflation in HostActivity:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    final MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.host_menu, menu);
    return super.onCreateOptionsMenu(menu);
}

The Problem

When I add menu items in NoteActivity, I achieve the desired order as expected:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.notebook_menu, menu);
    return super.onCreateOptionsMenu(menu);
}

However, when I add menu items in NotebooksFragment, because of how Fragments work, onCreateOptionsMenu is called after the same method in HostActivity, resulting in HostActivity's menu items appearing before NotebooksFragment's.

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.notebooks_menu, menu);
    SearchView sv = new SearchView(getActivity());
    sv.setOnQueryTextListener(this);
    menu.findItem(R.id.search_notebooks).setActionView(sv);

    super.onCreateOptionsMenu(menu, inflater);
}

How can I achieve my desired menu ordering?

like image 229
Jon Willis Avatar asked Apr 17 '11 23:04

Jon Willis


1 Answers

You can try using android:menuCategory and android:orderInCategory to more manually specify your ordering.

Or, use onPrepareOptionsMenu() in HostActivity, as that is called after onCreateOptionsMenu(). Downside is that it is called on every MENU button press, not just the first time.

like image 190
CommonsWare Avatar answered Nov 06 '22 01:11

CommonsWare