我的申请中有以下片段:
public class MyFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
private MenuItem refresh = null;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
//.....
// NPE here
refresh.setActionView(R.layout.indeterminate_progress_action);
getActivity().getSupportLoaderManager().initLoader(0, null, this);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.refresh_menu, menu);
refresh = (MenuItem) menu.findItem(R.id.menu_item_refresh);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
refresh.setActionView(null);
}
}
基本上当用户启动Activity时,我想在操作栏中显示进度微调器,直到加载器完成。在Android 4.2之前一切正常。在Android 4.2上,我收到以下错误:
11-24 13:37:14.811: E/AndroidRuntime(17850): Caused by: java.lang.NullPointerException
11-24 13:37:14.811: E/AndroidRuntime(17850): at com.MyApp.library.fragments.MyFragment.onActivityCreated(TabFragment.java:65)
添加一些断点后,我意识到onCreateOptionsMenu在onActivityCreated之后被调用。我可以使用另一个生命周期事件吗?是否有更好的方法来达到预期的效果?
答案 0 :(得分:3)
我以这种方式使用onPrepareOptionsMenu
来实现您的目标。
(未经测试但应该给你一个想法。)
private boolean mIsLoading = true;
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
refresh = (MenuItem) menu.findItem(R.id.menu_item_refresh);
if (!mIsLoading) {
refresh.setActionView(null);
}
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
mIsLoading = false;
getActivity().invalidateOptionsMenu();
}