Android:动态表格布局

Android : Dynamic TableLayout

我的目标是从数据库中获取数据,然后在我的应用程序中将其显示为 table。

这是我的代码:

 public void updateLastExpenses(){
    Cursor c = Expense.getAll(this);

    TableLayout lastExpensesTable = (TableLayout)findViewById(R.id.lastExpensesTable);

    lastExpensesTable.setStretchAllColumns(true);

    while (c.moveToNext()) {

        String name = c.getString(
                c.getColumnIndexOrThrow(ExpenseContract.ExpenseEntry.COLUMN_NAME_NAME)
        );
        float amount = c.getFloat(
                c.getColumnIndexOrThrow(ExpenseContract.ExpenseEntry.COLUMN_NAME_AMOUNT)
        );

        String date =  c.getString(
                c.getColumnIndexOrThrow(ExpenseContract.ExpenseEntry.COLUMN_NAME_DATE)
        );

        TableRow tr = new TableRow(this);

        TextView c1 = new TextView(this);
        c1.setText(name);
        c1.setBackgroundColor(Color.RED);

        TextView c2 = new TextView(this);
        c2.setText(""+amount);
        c2.setBackgroundColor(Color.BLUE);


        tr.addView(c1);
        tr.addView(c2);

        lastExpensesTable.addView(tr);

    }

}

这是我的 TableLayout:

<TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/lastExpensesTable">
            <TableRow
                android:id="@+id/lastExpensesTableRow"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <TextView
                    android:id="@+id/lastExpensesTableName"
                    android:text="@string/last_expenses_table_name"/>
                <TextView />
                <TextView
                    android:id="@+id/lastExpensesTableAmount"
                    android:text="@string/last_expenses_table_amount"/>
                <TextView />
            </TableRow>
        </TableLayout>

但这是结果:

你知道为什么内容都在 "name" 栏中,而不是分成两栏吗? 有没有更简洁的方法(我猜是通过使用布局并避免 .java 文件中的样式?)

提前致谢。

您的布局中有杂乱的 TextView

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lastExpensesTable">
        <TableRow
            android:id="@+id/lastExpensesTableRow"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <!-- first column -->
            <TextView
                android:id="@+id/lastExpensesTableName"
                android:text="@string/last_expenses_table_name"/>
            <!-- second column -->
            <TextView />
            <!-- third column -->
            <TextView
                android:id="@+id/lastExpensesTableAmount"
                android:text="@string/last_expenses_table_amount"/>
        </TableRow>
    </TableLayout>

取出标有"second column"的TextView,一切就绪。