问题描述
我在我的应用程序下面的代码片段:
I have the following fragment in my application:
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);
}
}
基本上当用户开始我想要显示进度微调,在动作条,直到加载完成的活动。在此之前的Android 4.2一切正常。在Android 4.2出现以下错误:
Basically when the user starts the Activity I want to display a progress spinner, in the actionbar, until the loader completes. Prior to Android 4.2 everything worked fine. On Android 4.2 I get the following error:
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后。是否有另一种生命周期事件中,我可以使用吗?有没有更好的是要达到预期的效果?
After adding some break point I realized onCreateOptionsMenu was getting called after onActivityCreated. Is there another life cycle event I can use? Is there a better was to achieve the desired effect?
推荐答案
我用在prepareOptionsMenu
以这种方式来达到你想要做什么。(未经测试,但应该给你一个想法。)
I've used onPrepareOptionsMenu
in this way to achieve what you are trying to do.(not tested but should give you an idea.)
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();
}
这篇关于onCreateOptionsMenu onResume后呼吁JB 4.2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!