Search code examples
androidandroid-tablelayout

TextView programmatically added to TableLayout doesn't match parent's width


I want to create a TableLayout with two columns. The first column would display drawable inside ImageView and should have the width of the picture. The second column should take all the remaining space (so match row's width).

TableLayout(context).apply {
    myList.forEach {
        val tableRow = TableRow(context)
        tableRow.setBackgroundColor(Color.GREEN)

        tableRow.addView(ImageView(context).apply {
            setImageResource(R.drawable.ic_blabla)
        })

        tableRow.addView(TextView(context).apply {
            text = it.code.toString()
            setBackgroundColor(Color.YELLOW)
            layoutParams = TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                                                 TableRow.LayoutParams.WRAP_CONTENT)
        })

        addView(tableRow)
    }

    myLinearLayout.addView(this)
}

Table layout is programmatically added to the linear layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/myLinearLayout"/>

As a result, I get two columns but both have the width of the content. The row has a green background so I can see that it has the width of the screen but the second column with yellow background has the width of the text displayed inside.

enter image description here

Any idea how can I set the second column width to take all that space?


Solution

  • Set layout_weigth="1" attribute to the column, it will assign additional importance to the view, so the column will be able to fill more space on the screen.