Abhinav Arora Abhinav Arora - 6 months ago 42
Android Question

Dynamically setting the table layout

I am trying to dynamically set a table layout in an activity. The number of rows and columns depend upon the user's input.

So the problem - Every time number of rows are fine but number of columns (textViews) in each row is always equal to the lowest value of the array

no_periods[ ]
. For eg. if no_days has a value 5,
have 2, 3, 4, 5, 6 values. The table will have 5 rows but each row will have only 2 textViews instead of 2, 3, 4, 5, 6 textViews in the respective rows.

Here is the code I am trying with

//loop to set the rows and text view in the table layout of activity_home
for (int i = 0; i < no_days; i++) {

tableRow = new TableRow(TimeTable.this);

for (int j = 0; j <no_periods[i]; j++) {

textView = new TextView(TimeTable.this);

int maxpixels = screenWidth/(no_periods[i]);
int minpixels = maxpixels;

textView.setPadding(10, 10, 10, 10);






Instead of setting max and minWidth, use TableRow weight:

textView.setPadding(10, 10, 10, 10);

tableRow.addView(textView, new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1));

This will distribute horizontal space among the TextViews in each row.

PS. You will probably want to use textView.setGravity(Gravity.CENTER); too.