如何从片段中获取列表视图?

How to get listview from fragment?

onCreateView 无法加载 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);

此代码有效

如何从fragment linearlayout中调用listview?

像这样更改代码

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.

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

FragmentonCreateView()中,替换

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

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

进一步考虑:

如果您改用 ListFragment,则可以通过调用 getListView()(在 onCreateView() returns 之后)直接获得对 ListView 的引用).您甚至不需要用这种方法膨胀 View,只需在 super() 构造函数中传递列表行布局并调用 setListAdapter().

编辑:

对于 IllegalStateException 错误,问题在于您将 View 视为子项,但 View 已经有父项。问题在这里:

1. ViewPager with a ListView fragment.

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

下面的代码对我有用。

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