Android Studio Kotlin开发:如何用for循环处理EditText输入生成配料列表
核心问题梳理
- 变量作用域错误:wetList、dryList、batterList定义在MainActivity类外部,属于全局顶层变量,不符合安卓Activity开发规范,易出现内存泄漏和数据异常
- batterList结构错误:当前
val batterList = arrayOf(wetList)是将整个湿性配料列表作为数组的唯一一个元素,没有包含干性配料列表,遍历该数组得到的item是完整列表而非单个配料 - 混合逻辑错误:for循环内每次直接给cakeText.text赋值会覆盖上一次的内容,最终只会显示最后一条配料,完全不符合逐条展示的需求
- 存在拼写错误:计数文案中
dry indredients拼写错误,应为dry ingredients
修复后完整代码
class MainActivity : AppCompatActivity() { // 所有成员变量放到Activity内部 val wetList = mutableListOf<String>() val dryList = mutableListOf<String>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } fun wetButtonTapped(view: View) { val input = wetText.text.toString() // 空判断避免添加无效空配料 if (input.isNotEmpty()) { wetList.add(input) } wetText.text.clear() // 修正拼写错误 ingredientList.text = "You have ${wetList.count()} wet ingredients \n You have ${dryList.count()} dry ingredients" } fun dryButtonTapped(view: View) { val input = dryText.text.toString() if (input.isNotEmpty()) { dryList.add(input) } dryText.text.clear() ingredientList.text = "You have ${wetList.count()} wet ingredients \n You have ${dryList.count()} dry ingredients" } fun mixButtonTapped(view: View) { // 先清空原有内容 cakeText.text = "" // 合并两类配料得到总列表 val allIngredients = wetList + dryList // 按作业要求使用for循环遍历 for (item in allIngredients) { // 用append追加内容避免覆盖,每条配料单独占一行 cakeText.append("You added $item to the batter!\n") } } }
逻辑验证说明
作业要求的for循环已经在mixButtonTapped方法中实现,合并后的配料列表会被逐一遍历,每条配料都会按要求格式展示在cakeText中,完全符合开发需求。
内容的提问来源于stack exchange,提问作者kwitter
相关产品推荐
相关产品推荐

