New to android programming.
I have a layout XML, to which I want to add a list (with items from a database), formatted as a table.
Here\'s the code:
Ok, I think I have an answer for you.
You need to be more specific when you are specifying LayoutParams. While it doesn't throw a compile exception, if you don't specify the correct parent class of the LayoutParams, nothing will show up.
When you specify layout params, you need to use the class of the container where the object is going. If you are setting the layout paramters of a textview that is going inside a LinearLayout, you would use new LinearLayout.LayoutParams(...)
similarily if you are creating a textview to go inside a TableRow, you need to use TableRow.LayoutParams(...)
Below is the full code with minor modifications because I didn't have a db setup.
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.edit_cat);
//Create table layout for the categories
TableLayout catList = new TableLayout(this);
//Set the table layout to Match parent for both width and height
// Note: We use LinearLayout.LayoutParams because the TableLayout is going inside a LinearLayout
catList.setLayoutParams(
new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
//Iterate the categories, and organize in tables
for(int i = 0; i < 5; i++)
{
TableRow tr = new TableRow(this);
/* Since the table row is going inside a table layout, we specify the parameters using TableLayout.LayoutParams */
tr.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
//Display category name
TextView name = new TextView(this);
/* Since the TextView is going inside a TableRow, we use new TableRow.LayoutParams ... */
name.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
name.setText("Test Row - " + i);
name.setBackgroundColor(Color.RED);
//Display category type
TextView type = new TextView(this);
type.setText("Type Row - " + i);
type.setBackgroundColor(Color.GREEN);
type.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
//Display edit button
Button btnEdit = new Button(this);
btnEdit.setText("Edit");
btnEdit.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
//Display delete button
Button btnDelete = new Button(this);
btnDelete.setText("Delete");
btnDelete.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
tr.addView(name);
tr.addView(type);
tr.addView(btnEdit);
tr.addView(btnDelete);
catList.addView(tr);
}
mainLayout.addView(catList);