Search code examples
androidkotlinandroid-tablelayout

Dynamically generating a table with buttons using Kotlin for Android


The finished goal is to be a series of buttons (currently in a table) which will hide/reveal rows containing fixed data between each.

I'm not sure if my approach is feasible or optimal, and I am not attached to this method. I have little experience with Kotlin/Android, but here's an example of what a hard coded sample looks like:

<TableLayout
    android:id="@+id/superTable"
    android:layout_width="match_parent"
    android:layout_height="0sp"
    android:layout_marginTop="0sp"
    android:stretchColumns="1"
    android:visibility="visible"
    app:layout_constraintTop_toBottomOf="@+id/chem2Table">

    <FrameLayout
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/superTableButton1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16sp"
            android:layout_marginLeft="16sp"
            android:layout_marginTop="0sp"
            android:onClick="superChemical1"
            android:text="@string/button_chem3"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/chem2Table" />
    </FrameLayout>

    <TableRow
        android:id="@+id/superRow1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="gone">

        <TextView
            android:id="@+id/sr1c1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="#b0b0b0"
            android:padding="5sp"
            android:text="@string/chem3c1"
            android:textColor="#000"
            android:textSize="12sp" />

</TableLayout>

and my hide/show method:

fun superChemical1(view: View) {
    val chemId = R.id.superRow1
    val chemVisibility = findViewById<TableRow>(chemId)

    if(chemVisibility.visibility == View.VISIBLE) {
        chemVisibility.visibility = View.GONE
    } else {
        chemVisibility.visibility = View.VISIBLE
    }
}

The goal would be to reproduce the same functionality, with the entire table being dynamically generated from an external source. It would be using a dynamic onClick method that can receive the ID of the clicked button, and then hide/show the next row which contains associated data.

The main thing I am not sure how to accomplish is associating each generated button with the following data row.


Solution

  • In the end, I decided to go with a RecyclerView which suits my purposes perfectly. TableLayout ended up becoming bulky and janky to format, so I scrapped the project and restarted with a RecyclerView.