Search code examples
listkotlinandroid-edittext

Making a list of lists of lists of EditText in Kotlin


I am fairly new to Kotlin and am trying to develop an app which requires me to access all EditText data from a table, that I generate programmatically also with Kotlin. That I managed to do, but I have been unsuccessful in creating lists that will hold all those instances of EditText. To sum it up, I need:

  1. Main list that will hold a few other lists, each for one person (the table is for recording arrow scores in archery)
  2. The secondary player lists will each hold several (let's say around 20) smaller lists
  3. These lists will contain a few EditText objects each.
var recordData = List(columns) { mutableListOf<MutableList<out Any>>() }

// create a row in the header table with the archer's names
val firstRow = TableRow(this)
var view1 = TextView(this)
view1.text = "  "
firstRow.addView(view1)

archers.forEach { i ->
    var name = TextView(this)
    name.text = i.toString().uppercase()
    name.setTextColor(Color.parseColor("#E2A300"))
    name.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20F)
    firstRow.addView(name)
    var playerArray = List(rows) { mutableListOf<EditText>() }
    recordData += playerArray
}

This is the kotlin code where I generate the table and try to initialize the first two lists. However, the last line creates this error:

Type mismatch: inferred type is List<MutableList> but List<MutableList<MutableList>> was expected

I tried doing this with also with Arrays, but hit essentially the same problem - how do I initialize a list/array of lists/arrays of lists/arrays of EditText? I have been stuck at this for a couple of hours so I'd be very grateful for any advice.


Solution

  • Try this:

    val recordData: MutableList<MutableList<EditText>> = mutableListOf()
    ...
    ...
    ..
    archers.forEach { i ->
        var name = TextView(this)
        name.text = i.toString().uppercase()
        name.setTextColor(Color.parseColor("#E2A300"))
        name.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20F)
        firstRow.addView(name)
    var playerArray: MutableList<EditText> = MutableList(rows) { EditText(this) } //edit
        recordData.add(playerArray)
    }