【发布时间】: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