I have a TableLayout in my app, which I need to define and add programmatically, as it builds upon the output of an SQL query. Basically, the result should look similar to a timetable (7 columns for each day in a week, multiple rows for different timeslots per day). For the cells/timeslots, I just need ordinary views with a certain background colour.
The problem is, that all views end up with a height and width of 0, although defined otherwise. What am I doing wrong?
Code:
RelativeLayout.LayoutParams tableLayout = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
tableLayout.addRule(RelativeLayout.BELOW, R.id.myOtherLayout);
tableLayout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
TableLayout table = new TableLayout(this);
table.setBackgroundColor(Color.WHITE);
table.setMinimumHeight(PixelConverter.pxToSp(this, 240));
// get availability table data
int[][] tableData = getTableData(...);
if (availability != null) {
// init array of tablerows, which represent one line each for every timeslot
for (int timeSlot = 0; timeSlot < 12; h++) {
// init row
TableRow newRow = new TableRow(this);
newRow.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, // width
10)); // height
newRow.setMinimumHeight(10);
// create 7 views in each row - one for each day in a week
for (int day = 0; day < 7; d++) {
View v = new View(this);
v.setLayoutParams(new LinearLayout.LayoutParams(
10, // TODO width
10)); // height
v.setMinimumWidth(10);
v.setMinimumHeight(10);
int cellHue = tableData[day][timeSlot];
if (cellHue >= 0) {
v.setBackgroundColor(Color.HSVToColor(new float[] { cellHue, 100, 100 }));
} else {
v.setBackgroundColor(Color.TRANSPARENT);
}
// add view to tablerow
newRow.addView(v, day);
}
table.addView(newRow, timeSlot);
}
}
table.setId(R.id.my_table_id);
mainLayout.addView(table, tableLayout);
I’ve encountered a similar issue – the problem appears to be with the choice of type of
LayoutParamsused after inflating your views. Particularly, the following is probably the root of your problem:I’d suggest that you try:
The key is that you apparently should specify the type of the parent view when using
LayoutParams, rather than the type of the view that you’re setting them on. Note that in this case, you’ll probably need to specifyTableLayout.LayoutParamswhen callingsetLayoutParamson your row, too.I don’t know how well documented this is – I noticed it mentioned on an arbitrary blog I’d found (lost the link now, alas) and I haven’t had chance to go back to the official documention yet, but presumably it’s there somewhere… 🙂
Hope this helps!