Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListFragment onPrepareOptionsMenu called before onCreate. Why and How to Fix / Bypass?

Okay, so I've got FavoritesList extending GalleryList which extends ListFragment:

public static class FavoritesList extends GalleryList {

    public static FavoritesList newInstance(int page) {
        FavoritesList list = new FavoritesList();

        Bundle args = new Bundle();
        args.putInt("page", page);
        list.setArguments(args);

        return list;
    }

    @Override
    public void onCreate(Bundle saveInstanceState) {
        super.onCreate(saveInstanceState);

        Cursor cursor = dbHelper.getGalleries(fav, preferences.getString("sort"+fav, "date desc"));
        listAdapter = new GalleryListAdapter(activity, cursor);
        setListAdapter(listAdapter);
    }

    ...

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.add(Menu.NONE, 0, 8, "Remove All");
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);

        //listAdapter is null the first time this is called...

        if (listAdapter != null && listlistAdapter.getCount() == 0) {
            menu.findItem(R.id.filter).setEnabled(false);
            menu.findItem(0).setEnabled(false);
        }
        else {
            menu.findItem(R.id.filter).setEnabled(true);
            menu.findItem(0).setEnabled(true);
        }
    }
}

Here is the problem: onPrepareOptionsMenu is called before onCreate (where I initialize listAdapter) when loading this Fragment, and it isn't called again before the options menu is shown for the first time!

The Fragment documentation is simply wrong when it claims onPrepareOptionsMenu "is called right before the menu is shown, every time it is shown."

p.s. I'm using the Android Support Library (v4). Any ideas?

like image 918
Michael Plotke Avatar asked Sep 11 '12 17:09

Michael Plotke


1 Answers

Try calling invalidateOptionsMenu() on your onCreate(). Make sure to check if your list adapter is null on onPrepareOptionsMenu().

like image 191
Chris Arriola Avatar answered Oct 13 '22 20:10

Chris Arriola