用数据数组填充 table

Populating a table with an array of data

我想设置一个 table,它有固定数量的列和 X 行,第一行列出每列的内容。例如,一列将是 'Name',第二列将是 'Age',那么将有 X 行来存储数据。有什么方法可以让我在其他地方为这些数据设置数组,并自动 create/fill table 的行与这些数据。我之前使用自定义适配器通过一个更简单的示例完成了此操作,但我不太确定如何处理涉及 table 的问题。我很困,任何帮助将不胜感激。

我想在 table 布局中创建如下 table 行

<TableLayout
---
>
<TableRow
--
>
<Textview
for name
/>
<Textview
...for age
/>

</TableRow>
<TableRow
--
>
<Listview
for name
/>
<Listview
...for age
/>

</TableRow>

</TableLayout>

并使用带有固定数据的简单数组适配器填充列表视图。

如果您的列表视图中只有文本视图,这很简单,您可以使用

ArrayAdapter ad=new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item1,namearray); list1.setAdapter(ad);

ArrayAdapter ad=new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item1,agearray); list2.setAdapter(ad);

A ListView 基本上充当任何 table 数据中的一行。您应该创建一个 POJO,其中包含您想要在一行中显示的所有属性。您可以为数据创建自定义 xml 布局,这可能是与您的列相对应的水平 LinearLayout

POJO

public class MyData {
    public String Name;
    public int Age;
    // More data here
}

ListView 项目布局(layout_list_item.xml)

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

        <TextView
            android:id="@+id/Name"
            android:layout_height="wrap_content"
            android:layout_width="0dip"
            android:layout_weight="0.7" />

        <TextView
            android:id="@+id/Age"
            android:layout_height="wrap_content"
            android:layout_width="0dip"
            android:layout_weight="0.3" />

    </LinearLayout>

主要布局

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_height="wrap_content"
                android:layout_width="0dip"
                android:layout_weight="0.7"
                android:text="Name" />

            <TextView
                android:layout_height="wrap_content"
                android:layout_width="0dip"
                android:layout_weight="0.3"
                android:text="Age" />

        </LinearLayout>

        <ListView
            android:id="+@id/MyDataListView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>

     </LinearLayout>

然后您需要一个自定义适配器,它使用您的 POJO 中的值设置列表视图中的字段。网上有很多这方面的教程。