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

后端 未结 2 1885
执念已碎
执念已碎 2021-01-12 02:07

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

public static class FavoritesList         


        
相关标签:
2条回答
  • 2021-01-12 02:50

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

    0 讨论(0)
  • 2021-01-12 02:52

    So, as silly as this is, here is a functioning workaround:

    public static class FavoritesList extends GalleryList {
    
        Menu optionsMenu;
    
        ...
    
        @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);
    
            if (optionsMenu != null) {
                onPrepareOptionsMenu(optionsMenu);
            }
        }
    
        ...
    
        @Override
        public void onPrepareOptionsMenu(Menu menu) {
            super.onPrepareOptionsMenu(menu);
    
            optionsMenu = menu;
    
            if (listAdapter != null && listAdapter.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);
            }
        }
    }
    

    Basically I've grabbed the options menu during the first run of onPrepareOptionsMenu, then called it again once listAdapter has been initialized.

    edit: evidently without checking if optionsMenu is null, this will break on certain phones. I should have realized.

    0 讨论(0)
提交回复
热议问题