【问题标题】:How create a button by programmatically for a GridLayout如何以编程方式为 GridLayout 创建按钮
【发布时间】:2021-03-09 10:14:37
【问题描述】:

我正在尝试通过在 Kotlin 中以编程方式创建 GridLayout。我的 XML 代码是这样的:

<androidx.constraintlayout.widget.ConstraintLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:background="#46FF4433"
      tools:context=".MainActivity">

     <androidx.gridlayout.widget.GridLayout
        android:id="@+id/grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:rowCount="5">
        app:columnCount="3"
     </androidx.gridlayout.widget.GridLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

我想在我的网格中设置 15 个按钮。我的 mainActivity 是这样的:

    val gridLayout: GridLayout = findViewById(R.id.grid)

    for (i in 1..10){
        val button = Button(this)
        button.text = "Boton: " + i
        button.setBackgroundColor(Color.parseColor("#ffffff"));

        gridLayout.addView(button)

    }

但我需要每个按钮都是这样的:

    <Button
        android:id="@+id/button1"

        app:layout_gravity="fill"
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"

        android:text="Button 1"
        android:background="#ffffff"
    />

我认为这与布局参数有关,但我不知道如何设置这些属性。

【问题讨论】:

  • 使用网格适配器并重新运行其大小 15,而不是将按钮文本设置为适配器

标签: android android-layout kotlin button


【解决方案1】:

看看GridLayout.LayoutParamsGridLayout.Spec。您可以执行以下操作:

val button = Button(this)
val lp = GridLayout.LayoutParams()
lp.setGravity(Gravity.FILL)

// GridLayout.spec is immutable, so one can be applied more than once.
// There are several other versions of GridLayout.spec which may be applicable.
lp.rowSpec = GridLayout.spec(row, 1.0f) // row start, weight
lp.columnSpec = GridLayout.spec(col, 1.0f) // column start, weight
button.layoutParams = lp

我尚未对此进行测试,但它应该可以帮助您入门。

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多