Android:动态TableLayout

时间:2015-03-30 00:59:09

标签: android layout tablelayout

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

这是我的代码:

 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>

但结果如下:

enter image description here

您知道为什么内容全部在“名称”列中而不是在两列之间分开吗? 是否有更简洁的方法(通过使用布局并避免使用.java文件中的样式?)

提前致谢。

1 个答案:

答案 0 :(得分:1)

您的布局中有一个迷路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>

取出TextView标记为&#34;第二列&#34;而且你已经完成了所有的设置。