You should use correct LayoutParams
for views.
While adding a view to:
TableLayout
; useTableLayout.LayoutParams
TableRow
; useTableRow.LayoutParams
.
Edit: I've edited the code. You want some black spaces for some cells. You can achive this with setting same bg color to that views(or transparent bg for row and views on cell). I think setting same bg color to textViews with tableLayout is easier.
Here is a complete code sample that you can try(colors are added to see output easily):
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TableLayout tableLayout = createTableLayout(16, 14);
setContentView(tableLayout);
makeCellEmpty(tableLayout, 1, 6);
makeCellEmpty(tableLayout, 2, 3);
makeCellEmpty(tableLayout, 3, 8);
makeCellEmpty(tableLayout, 3, 2);
makeCellEmpty(tableLayout, 4, 8);
makeCellEmpty(tableLayout, 6, 9);
}
public void makeCellEmpty(TableLayout tableLayout, int rowIndex, int columnIndex) {
// get row from table with rowIndex
TableRow tableRow = (TableRow) tableLayout.getChildAt(rowIndex);
// get cell from row with columnIndex
TextView textView = (TextView)tableRow.getChildAt(columnIndex);
// make it black
textView.setBackgroundColor(Color.BLACK);
}
private TableLayout createTableLayout(int rowCount, int columnCount) {
// 1) Create a tableLayout and its params
TableLayout.LayoutParams tableLayoutParams = new TableLayout.LayoutParams();
TableLayout tableLayout = new TableLayout(this);
tableLayout.setBackgroundColor(Color.BLACK);
// 2) create tableRow params
TableRow.LayoutParams tableRowParams = new TableRow.LayoutParams();
tableRowParams.setMargins(1, 1, 1, 1);
tableRowParams.weight = 1;
for (int i = 0; i < rowCount; i++) {
// 3) create tableRow
TableRow tableRow = new TableRow(this);
tableRow.setBackgroundColor(Color.BLACK);
for (int j= 0; j < columnCount; j++) {
// 4) create textView
TextView textView = new TextView(this);
textView.setText(String.valueOf(j));
textView.setBackgroundColor(Color.WHITE);
textView.setGravity(Gravity.CENTER);
// 5) add textView to tableRow
tableRow.addView(textView, tableRowParams);
}
// 6) add tableRow to tableLayout
tableLayout.addView(tableRow, tableLayoutParams);
}
return tableLayout;
}
And here is the output for this code that we can see margins are applied correctly: