我有一个扩展的ListFragment,使用这个onViewCreated()
public void onViewCreated(View v,Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
mListener.onFragmentAction(0x000A);
if (mAdapter != null) {
getListView().setAdapter(mAdapter);
}
}
mListener.onFragmentAction调用main活动来附加一些侦听器并将适配器发送到片段的listView(logFrag
是活动对MyListFragment
的引用)
public void populateLogFrag() {
//line 225 logFrag.getListView().setOnItemLongClickListener(myEventListener);
logFrag.getListView().setOnItemClickListener(myEventListener);
refreshLogAdapter(provideLogAdapter());
}
应用程序加载正常,但在配置更改(设备轮换)后,我得到以下堆栈跟踪:
11-22 14:58:24.336: E/AndroidRuntime(22261): Caused by: java.lang.IllegalStateException: Content view not yet created
11-22 14:58:24.336: E/AndroidRuntime(22261): at android.support.v4.app.ListFragment.ensureList(ListFragment.java:328)
11-22 14:58:24.336: E/AndroidRuntime(22261): at android.support.v4.app.ListFragment.getListView(ListFragment.java:222)
11-22 14:58:24.336: E/AndroidRuntime(22261): at com.berrmal.timetracker.MainActivity.populateLogFrag(MainActivity.java:225)
11-22 14:58:24.336: E/AndroidRuntime(22261): at com.berrmal.timetracker.MainActivity.onFragmentAction(MainActivity.java:282)
11-22 14:58:24.336: E/AndroidRuntime(22261): at com.berrmal.timetracker.MyListFragment.onViewCreated(MyListFragment.java:23)
我无法弄清楚为什么尚未创建ListView,因为我在片段的onCreateView方法已经返回之后以及onViewCreated()期间调用它。我找到了一两个相关标题的主题,但解决方案似乎并不适用于此。
答案 0 :(得分:26)
将代码从onViewCreated
移至onActivityCreated
。通常,使用UI小部件的所有内容都应该在onActivityCreated
。