-1

onCreateView无法加载的ListView如何从片段获取listview?

mDrawerListView = (ListView) getActivity().findViewById(R.id.navigation_list); 

在该上代码

mDrawerListView是空对象

这是fragment_navation_drawer.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:id="@+id/drawer_layout" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent"> 

    <ListView xmlns:android="http://schemas.android.com/apk/res/android" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:background="#cccc" 
       android:choiceMode="singleChoice" 
       android:divider="@android:color/transparent" 
       android:id="@+id/navigation_list" 
       android:dividerHeight="0dp"/> 

</LinearLayout> 

如果我不使用的LinearLayout并且只使用ListView

<ListView xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent" 
        android:background="#cccc" 
        android:choiceMode="singleChoice" 
        android:divider="@android:color/transparent" 
        android:id="@+id/navigation_list" 
        android:dividerHeight="0dp"/> 

这样的XML和使用

mDrawerListView = (ListView) inflater.inflate(
       R.layout.fragment_navigation_drawer, container, false); 

这个代码是工作

如何从片段的LinearLayout调用列表视图?

变化这样的代码

mDrawerListView = (ListView) inflater.inflate(
       R.layout.fragment_navigation_drawer, container, false).findViewById(R.id.navigation_list); 

这可以调用的ListView但其他错误

Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. 
+0

[片段中的onCreateView()方法的NullPointerException(http://stackoverflow.com/questions/15202107/nullpointerexception-in-fragments-oncreateview-method)bazillion的可能重复...等 – Selvin 2015-04-03 14:20:14

回答

3

假设mDrawerListView处于View层次结构中的Fragment(而不是导航抽屉)的ListView,错误的原因是FragmentView层次尚未创建。

FragmentonCreateView(),更换

mDrawerListView = (ListView) getActivity().findViewById(R.id.navigation_list); 

mDrawerListView = (ListView) rootView.findViewById(R.id.navigation_list); 

进一步考虑:

如果你使用一个ListFragment代替,你可以直接得到一个致电参考(onCreateView()返回后)。您甚至不需要用这种方法对View充气,只需在super()构造函数中传递列表行布局并调用setListAdapter()即可。

编辑:

对于IllegalStateException错误,问题是,你正在处理View作为一个孩子,但View已经有母。这里覆盖的问题是:

1.ViewPager with a ListView fragment

2.Fragments - The specified child already has a parent.

+0

是什么“rootView”?当这个rootView创建? – user2637015 2015-04-03 14:20:33

+0

'rootView'是'View'从XML布局充气用于'Fragment'在'onCreateView()'。使用吹气和成功调用列表视图,但其他错误 – 2015-04-03 14:23:22

+0

电话根本观点是发生:(指定的孩子已经有一个父 – user2637015 2015-04-03 14:33:58

0

以下代码适用于我。

ListView listView = getListView(); 
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
       @Override 
       public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { 
        Log.e("onItemClick", "onItemClick"); 
       } 
      });