Search code examples
androidandroid-studiokotlingridgrid-layout

Fill a GridLayout from Kotlin


I'm android studio noob. I'm trying to fill a grid layout from kotlin activity.

My code for the xml is this:

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

</androidx.gridlayout.widget.GridLayout>

In the MainActivity there is a for to create every buttom like this:

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

for (i in 1..10){
   val button = Button(this)
   button.text = "Boton: " + i

   // GridLayout.add(Buttom)
        
}

Who can I do it?

Thank you


Solution

  • Modify Your Function as Per the given Code.

         for (i in 1..10){
            val button = Button(this)
            button.text = "Boton: " + i
            val param = GridLayout.LayoutParams(
                GridLayout.spec(
                    GridLayout.UNDEFINED, GridLayout.FILL, 1f
                ),
                GridLayout.spec(GridLayout.UNDEFINED, GridLayout.FILL, 1f)
            )
    
            button.layoutParams = param
            gridLayout.addView(button)
    
        }