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

如何在Android Jetpack Compose中运行时添加TextField并管理其取值

问题核心与修复方案

你现有代码的核心问题是状态管理逻辑错误:所有行共用同一个价格状态、重量状态的读写索引错误、新增行时没有同步初始化对应状态条目。

修正思路

  • 定义数据类统一存储每行的重量、价格数据
  • 使用mutableStateListOf存储所有行的状态,新增行时同步添加空初始条目
  • 每行的输入框单独绑定对应索引的状态,修改时只更新对应位置的数据

修正后代码

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

// 定义每行的费率数据结构
data class RateItem(
    var weight: String = "",
    var price: String = ""
)

@Composable
fun ComposeTextFields() {
    // 存储所有行的费率数据
    val rateItems = remember {
        mutableStateListOf<RateItem>()
    }

    Column {
        LazyColumn {
            items(rateItems.size) { index ->
                val currentItem = rateItems[index]
                Row {
                    OutlinedTextField(
                        value = currentItem.weight,
                        onValueChange = { 
                            // 仅更新当前行的重量
                            rateItems[index] = currentItem.copy(weight = it) 
                        },
                        label = { Text(text = "Weight") },
                        modifier = Modifier.weight(1f)
                    )
                    OutlinedTextField(
                        value = currentItem.price,
                        onValueChange = { 
                            // 仅更新当前行的价格
                            rateItems[index] = currentItem.copy(price = it)
                        },
                        label = { Text(text = "Price")},
                        modifier = Modifier
                            .weight(1f)
                            .padding(start = 5.dp)
                    )
                }
            }
            item {
                TextButton(onClick = { 
                    // 新增行时同步添加空数据条目
                    rateItems.add(RateItem()) 
                }) {
                    Text("more ${rateItems.size}")
                }
            }
        }
    }
}

运行说明

点击添加按钮时会自动新增一行空白输入框,每行的重量、价格输入互不干扰,所有输入的数据都会保存在rateItems列表中,后续提交数据时直接遍历该列表即可获取所有档位的费率信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:27:02