androidkotlinandroid-tablelayout

Can not fill layout dynamically (Kotlin Android)


I need to create a TableLayout with any specified number of rows and columns and fill it with any views.

That's what I tryed:

class GameFragment : Fragment() {

    private lateinit var binding: FragmentGameBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
    

        binding = DataBindingUtil.inflate(
            inflater,
            R.layout.fragment_game,
            container,
            false
        )
        binding.field.columnCount = 4
        binding.field.rowCount = 4


        for (i in 1..16){
            val button = Button(activity)
            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
            binding.field.addView(button)

        }
    }
}

XML:

        <GridLayout
            android:id="@+id/field"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toTopOf="parent">
        </GridLayout>

field.children contains all button i added, but i don't see any buttons on the screen. I need solution that allows to create GridLayout with any row and column count. Thanks in advance


Solution

  • As I don't see what you return from onCreateView, so did you forget to return binding.root in onCreateView?