Android GridLayout layout_columnWeight="1" 和 layout_width="0dp" 以编程方式

Android GridLayout layout_columnWeight="1" and layout_width="0dp" programmatically

我使用 GridLayout 并希望以编程方式添加视图。

我希望所有视图均分,但遇到一些问题。

我的问题:(600宽度和700宽度不相等)

我要:

xml:

  <GridLayout
                        android:id="@+id/withdrawSettingLayout"
                        android:layout_width="match_parent"
                        android:useDefaultMargins="true"
                        android:layout_height="wrap_content"
                        android:columnCount="4"/>

Kotlin 代码:

list.forEach { amount->

    val titleText = TextView(context).apply {
        text = amount
        setTextColor(ContextCompat.getColor(context, R.color.white))
    }
    val layoutParams = GridLayout.LayoutParams(GridLayout.spec(GridLayout.UNDEFINED, 1f), GridLayout.spec(GridLayout.UNDEFINED, 1f))
    layoutParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1f)
    viewBinding.withdrawSettingLayout.addView(titleText, layoutParams)
}

如何解决,谢谢

不确定是否有帮助,但您可以尝试添加:

layoutParams.width = 0