问题
My goal is to get data from DB, and then display it as a table in my app.
Here is my code:
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);
}
}
And here is my 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>
But here is the result:
Do you know why the content is all in the "name" column and not split between the two columns? Is there a cleaner way to do it (by using layout and avoiding the styling in the .java file I guess?)
Thanks in advance.
回答1:
You have a stray TextView
in your layout.
<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>
Take out that TextView
marked "second column" and you're all set.
来源:https://stackoverflow.com/questions/29336880/android-dynamic-tablelayout