Using table layout in Android is pretty nasty. As a webdeveloper I’m known to the default behaviour of tables. Using table layout in Android, it’s completely different en you have to think in an other way.
To create equal width for the cells is painfully hard to create in de layout.xml. It’s even harder to create the table dynamically. I’ve searched the smallest area’s of the web but couldn’t find a single nice piece of code, so I had te create my own.
The end result will look like:


I’m talking about the second row of textviews which are placed inside a table layout, all with equal width.

So what’s the code:
First create the tablelayout in your xml:
[code lang=”xml”]
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tblScore"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_marginTop="1dp">
<TableRow android:id="@+id/questionRow">
</TableRow>
</TableLayout>
[/code]

And in your class, create textviews and place them insite the table row:
[code lang=”java”]
public void SetQuestionsInTopRow(int numberOfQuestions){
TableRow tr = (TableRow) findViewById(R.id.questionRow);
tr.setWeightSum(numberOfQuestions);
for (int i = 1; i <= numberOfQuestions; i++) {
tableScore.setColumnStretchable(i-1, true);
TextView tv = new TextView(this);
tv.setText(String.valueOf(i) + " ");
tv.setTextSize(12);
tv.setShadowLayer(1, 1, 1, this.getResources().getColor(R.color.black));
tv.setBackgroundResource(R.drawable.circle_black);
tv.setGravity(Gravity.CENTER_HORIZONTAL);
tv.setId(100+i);
tv.setTextColor(tv.getContext().getResources().getColor(R.color.white));
tr.addView(tv);
}
}
[/code]
Important in this code is the weightsom for the table row:
[code lang=”java”]
tr.setWeightSum(numberOfQuestions);
[/code]
and the setcolumnsstretchable for the table:
[code lang=”java”]
tableScore.setColumnStretchable(i-1, true);
[/code]

Thit code will create dynamically generated textviews inside a tablerow with equal width.