好的,所以我有了CameraList,扩展了GalleryList,扩展了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,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); } } }
这是问题:onPrepareOptionsMenu在加载此片段之前在onCreate(我初始化listAdapter)之前调用,并且在第一次显示选项菜单之前不再调用它!
当声明onPrepareOptionsMenu时,Fragment documentation在菜单显示之前被调用,每次显示时都是错误的.
附:我正在使用Android支持库(v4).有任何想法吗?
解决方法
尝试在onCreate()上调用invalidateOptionsMenu().确保在onPrepareOptionsMenu()上检查列表适配器是否为null.