Equal width in Android TableLayout

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:

    	android:layout_height="wrap_content" android:layout_marginTop="1dp">
	    <TableRow android:id="@+id/questionRow">

And in your class, create textviews and place them insite the table row:

public void SetQuestionsInTopRow(int numberOfQuestions){		
		TableRow tr = (TableRow) findViewById(R.id.questionRow);
		for (int i = 1; i <= numberOfQuestions; i++) {
			tableScore.setColumnStretchable(i-1, true);
			TextView tv = new TextView(this);
			tv.setText(String.valueOf(i) + " ");					
			tv.setShadowLayer(1, 1, 1, this.getResources().getColor(R.color.black));

Important in this code is the weightsom for the table row:


and the setcolumnsstretchable for the table:

tableScore.setColumnStretchable(i-1, true);

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


I'm a webdeveloper, looking for the best experience, working between development and design. Just a creative programmer. When I'm getting tired of programming C#, i'd love to create 3D images in 3D Studio Max, play the guitar, create an app for Android or crush some plastics on a climbing wall or try to stay alive when i´m descending some nice white powdered snowy mountains on my snowboard.

2 thoughts to “Equal width in Android TableLayout”

  1. Thanks a ton,
    I was searching for this solution and got meddled with all sort of layout parameter tricks which didn’t work. However your solution worked like charm. On points like this android developer documents also don’t provide correct way of getting things done. Would like to just ask you how you found out this solution? I regularly get stuck when going through android developer docs to find which functionality i need to fiddle with.
    Thanks again,

Leave a Reply to dheeraj suthar Cancel reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.