You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin创建EditText三级嵌套列表遇类型不匹配错误求助

问题描述

我是Kotlin新手,正在开发一款射箭分数记录APP,需要程序化生成表格并获取所有EditText的数据。目前表格生成已实现,但无法正确创建存储所有EditText实例的嵌套列表,需求如下:

  • 主列表:存储多个子列表,每个子列表对应一名玩家
  • 玩家子列表:每个包含约20个更小的列表
  • 最小列表:每个包含若干EditText对象

相关代码:

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
}

代码最后一行报错:Type mismatch: inferred type is List<MutableList<EditText>> but List<MutableList<MutableList<out Any>>> was expected,尝试用数组也遇到同类问题,求助如何正确初始化存储EditText的嵌套列表/数组。

解决方案

问题根源

  1. 类型不匹配:你初始化的recordData是List<MutableList<MutableList<out Any>>>,但要添加的playerArray是List<MutableList<EditText>>,三层结构和类型完全不匹配。
  2. 不可变列表无法添加元素:Kotlin中List()创建的是不可变列表,不能用+=添加新元素,必须使用可变的MutableList。

修正步骤

  1. 正确初始化嵌套可变列表:明确三层结构的泛型类型,确保每层都对应需求的存储对象:

    // 主列表:存储玩家子列表的可变列表
    // 玩家子列表:存储最小EditText列表的可变列表
    // 最小EditText列表:存储EditText的可变列表
    var recordData = mutableListOf<MutableList<MutableList<EditText>>>()
    
  2. 修改玩家子列表的创建方式:用MutableList()创建可变的玩家子列表,确保类型和主列表的元素类型匹配,同时用add()方法添加到主列表:

    archers.forEach { i ->
        // ... 头部TextView创建代码保持不变
        val playerArray = MutableList(rows) { mutableListOf<EditText>() }
        recordData.add(playerArray)
    }
    
  3. 添加EditText到最小列表:后续生成每个EditText时,把它添加到对应的最小列表中(示例代码):

    archers.forEachIndexed { archerIndex, i ->
        // ... 头部TextView创建代码保持不变
        val playerArray = MutableList(rows) { mutableListOf<EditText>() }
        recordData.add(playerArray)
        
        // 生成该玩家的所有表格行和EditText
        for (rowIndex in 0 until rows) {
            val row = TableRow(this)
            // 假设每行生成3个EditText
            for (count in 0 until 3) {
                val editText = EditText(this)
                editText.hint = "输入分数"
                row.addView(editText)
                // 将EditText存入对应玩家、对应行的最小列表
                recordData[archerIndex][rowIndex].add(editText)
            }
            yourTable.addView(row) // 将行添加到目标表格
        }
    }
    

后续数据获取示例

需要读取所有EditText的分数时,直接遍历嵌套列表即可:

recordData.forEachIndexed { archerIndex, playerRows ->
    playerRows.forEachIndexed { rowIndex, editTexts ->
        editTexts.forEach { editText ->
            val score = editText.text.toString().trim()
            // 处理分数数据,比如存入数据库或计算总分
        }
    }
}

内容的提问来源于stack exchange,提问作者Jayne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 11:52:08