首页 > 解决方案 > 以编程方式添加到 TableLayout 的 TextView 与父级的宽度不匹配

问题描述

我想TableLayout用两列创建一个。第一列将在内部显示drawable,ImageView并且应该具有图片的宽度。第二列应占用所有剩余空间(因此匹配行的宽度)。

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)
}

表格布局以编程方式添加到线性布局中:

<?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"/>

结果,我得到了两列,但都有内容的宽度。该行具有绿色背景,因此我可以看到它具有屏幕的宽度,但具有黄色背景的第二列具有内部显示的文本的宽度。

在此处输入图像描述

知道如何设置第二列宽度以占用所有空间吗?

标签: androidandroid-tablelayout

解决方案


为列设置layout_weigth="1"属性,它将为视图分配额外的重要性,因此列将能够在屏幕上填充更多空间。


推荐阅读