如何为Fragment中包含的ListView调用setListAdapter

时间:2011-09-11 15:49:43

标签: java android

我看到ListView的所有示例往往是ListActivityListFragment的实现,其中setListAdapter()事件中调用了onCreate()

但是,我希望ListView包含在另一个Fragment中,我不希望将ListView作为Fragment本身......如果你知道我的意思。

我想知道我的Fragment是否有这样的xml:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"
    android:textSize="40sp"
    >

    <ListView android:id="@+id/left_menu" android:layout_width="wrap_content" android:layout_height="wrap_content">
    </ListView>

</LinearLayout>

如何在片段类中为列表视图调用setListAdapter?我见过ListView中包含Activity的示例,您调用findViewById()获取ListView对象,然后调用setListAdapter()

但是,Fragment类没有findViewById方法,那么如何获得对ListView对象的引用?

3 个答案:

答案 0 :(得分:2)

只是一个免责声明,我自己并没有真正尝试过,但是从API文档中读取,您可以调用getView来获取片段的根视图。 据推测,您将通过onCreateView

实例化XML Layour

获得根视图后,我认为您可以通过通常的findViewById

访问ListView

答案 1 :(得分:1)

具体来说,片段可以使用getActivity()访问Activity实例,并轻松执行任务,例如在活动布局中查找视图:

View listView = getActivity().findViewById(R.id.list);

答案 2 :(得分:1)

我知道这件事来得晚,但我想我会回答,以防万一。您可以在普通片段中包含ListView,就像使用任何其他窗口小部件一样。而且你也可以在同一个片段中拥有其他几个小部件。在这种情况下,您使用onCreateView对片段进行膨胀,如下所示:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
    View view = inflater.inflate(R.layout.your_fragment, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    // I gave the default list id
    listView = (ListView) view.findViewById(android.R.id.list);
    listView.setAdapter(customAdapter); // your customAdapter should have already been initialzed at this point
    // Initialize other items  - Buttons, EditTexts... etc.
}

然后你就像对待任何ListAdapter对象一样对待它