使用适配器将 LinearLayout 添加到列表视图



我正在尝试创建一个ListView,其中列表中的每个条目都包含一个LinearLayout。我有一个我在这里定义的ArrayList

ArrayList<LinearLayout> menuList; .

在我的代码后面,我定义

LinearLayout dailyMenuLayout = new LinearLayout(ReturnMenus.this);,每次完成要添加到列表视图的布局时,我都会使用menuList.add(DailyMenuList)

我一直尝试使用的适配器如下 - 但每次触发时都会使应用程序崩溃。

ListView myListView = (ListView)findViewById(android.R.id.list); ArrayAdapter<LinearLayout> adapter = new ArrayAdapter<LinearLayout>(ReturnMenus.this, R.id.linear_layout_item, menuList); myListView.setAdapter(adapter);

这是列表视图中单行的 XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <LinearLayout
        android:id="@+id/linear_layout_item"
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="wrap_content" >
    </LinearLayout>
</LinearLayout>

有人可以告诉我如何做到这一点吗?谢谢。

对列表中的行布局(而不是当前布局)使用以下布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView 
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
     <TextView 
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
      <TextView 
        android:id="@+id/text3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
      .
      .
      .
      .
      .
    </LinearLayout>

在这里,如果您不知道要使用的文本视图的确切数量,请使用应用程序中使用的最大数量的 TextView。然后在 getView() 中的适配器类中,您可以获取这些 TextView。如果某些行不打算使用所有这些 textViews,则将它们设置为不可见,如下所示:

TextView txtView3 = (TextView)findViewById(R.id.text3);
txtView3.setVisibility(View.GONE)

以下教程可帮助您创建列表视图。http://www.vogella.com/tutorials/AndroidListView/article.html

您应该将数据绑定到适配器,例如字符串,而不是布局。

要了解如何使用 ListView 和 Adapter,请查看您的 android-sdk-dir\samples\android-XX\ApiDemos 中的演示项目。

最新更新