簡體   English   中英

如何以編程方式為 GridLayout 創建按鈕

[英]How create a button by programmatically for a GridLayout

我正在嘗試通過在 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 個按鈕。 我的主要活動是這樣的:

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

我認為這與布局參數有關,但我不知道如何設置這些屬性。

看看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

我沒有測試過這個,但它應該讓你開始。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM