我有一个扩展的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 Activity 来附加一些监听器,并将适配器发送到 fragment 的listView(logFrag是 Activity 对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,因为我是在Fragment的onCreateView方法已经返回之后以及在onViewCreated()期间调用它的。我发现一个或两个带有相关标题的主题,但是解决方案似乎在这里并不适用。

最佳答案

将代码从onViewCreated移到onActivityCreated。通常,所有使用UI小部件的东西都应该在onActivityCreated中。

10-07 19:47