user1004816 user1004816 - 1 month ago 16
Android Question

Generate symmetric table in Android

I got some trouble with the TableLayout Android. I wanna create a table with symmetric rows/columns, i.e. a layout where every TextView in it gets allocated exactly the same amount of space like all the others, no matter what text has been appended to it.

It's important that this can be done by the use of Java-code, not the XML-files.

It would be probably good to know that this layout requires two tables to be next to each other, i.e. every table has just 50% of the screen size. I suppose this makes several LayoutParameter unavailable (e.g. FILL_PARENT)?

This is what I tried:

for (String s : buffer) {
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(0x00, LayoutParams.WRAP_CONTENT, 1f));
tv.append(s);
row.addView(tv, new TableRow.LayoutParams(LayoutParams.FILL_PARENT));
}


Still looks bad though.

Answer

This will create two columns that share's the width in an orderly fashion.

<TableLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <TableRow>
        <!-- Set the width to 0dp and set layout_weight=1! on both Views-->
        <TextView
            android:text="This is text1, its pretty long but that shouldn't be a problem"
            android:layout_marginLeft="1px"
            android:background="#ff0000"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content" />

        <TextView
            android:text="Shorter"
            android:background="#00ff00"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content" />
    </TableRow>
</TableLayout>

Edit: Same thing, but now in code:

    TableLayout layout = new TableLayout(this);
    TextView t1 = new TextView(this);
    t1.setBackgroundColor(Color.BLUE);
    t1.setText("This is text1, its pretty long but that shouldn't be a problem");
    TextView t2 = new TextView(this);
    t2.setBackgroundColor(Color.GRAY);
    t2.setText("Shorter");

    TableRow row = new TableRow(this);
    row.addView(t1, new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f));
    row.addView(t2, new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f));

    layout.addView(row);