【问题标题】:How to create an array of editTexts using for loop on Kotlin - Android Studio如何在 Kotlin 上使用 for 循环创建一个 editTexts 数组 - Android Studio
【发布时间】:2021-11-18 05:25:26
【问题描述】:

在本周的课堂上,我们的任务是创建一个简单的蛋糕烘焙应用。有两个编辑文本字段(湿文本、干文本),用户可以在其中输入要添加到蛋糕中的成分。添加成分后单击一个混合按钮。在 mixbutton 单击时,我的目标是将添加的成分从 editText 列出到新的 textView(cakeText) 中,如下所示:

您在击球手中添加了 ---!
您在击球手中添加了 ---!
您在击球手中添加了 ---!
等等

我们应该使用 for 循环,我想我可能通过使用数组走在正确的轨道上。 batterList 是我最近的尝试,所以我知道这是错误的,但我很想知道如何解决它!我已经工作了几个小时并且已经接近了,但还不够接近。我希望这是有道理的。在这一点上,我的头脑不正常。任何建议将不胜感激!

    val wetList = mutableListOf<String>()
    val dryList = mutableListOf<String>()
    val batterList = arrayOf(wetList)



    class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}

fun wetButtonTapped(view: View) {
    wetList.add(wetText.text.toString())
    wetText.text.clear()
    ingredientList.text = "You have ${wetList.count()} wet ingredients \n You have ${dryList.count()} dry indredients"
}

fun dryButtonTapped(view: View) {
  dryList.add(dryText.text.toString())
    dryText.text.clear()
    ingredientList.text = "You have ${wetList.count()} wet ingredients \n You have ${dryList.count()} dry indredients"
}

fun mixButtonTapped(view: View) {
    //cakeText.text = "You added ${wetList}"
 for (item in batterList){
 cakeText.text = "You added $item to the batter!"
 }

【问题讨论】:

  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: android arrays list kotlin android-edittext


【解决方案1】:

您总是将预期列表的最后一行分配给cakeText

试试这个:

cakeText.text = "${cakeText.text}\nYou added $item to the batter!"

这应该在文本中一一添加项目。 此外,您可能需要将 batterListval 更改为 var 并在 mixButtonTapped 上重新分配它。所以最终的代码应该是这样的:

var batterList = arrayOf(wetList)
...

fun mixButtonTapped(view: View) {
batterList = arrayOf(wetList)
  for (item in batterList){
    cakeText.text = "${cakeText.text}\nYou added $item to the batter!"
  }
}

【讨论】:

    【解决方案2】:

    据我了解,您希望在单个文本视图中显示所有添加的成分。因此,与其声明一个有时可能无法管理的新数组,我将直接使用数组和 StringBuilder 类来构建整个字符串

    fun mixButtonTapped(view: View) {
    
        val stringBuilder = StringBuilder()
    
        // here (wetList + dryList) will be merged into single list
        for (item in (wetList + dryList))
            stringBuilder.append("You added $item to the batter!\n")
    
        cakeText.text = stringBuilder.toString()
    
    }
    

    所以我不会管理第三个数组,而是直接使用这两个数组并在我的任务完成时处理合并的数组,在这种情况下,它将是循环完成时。

    【讨论】:

      猜你喜欢
      • 2019-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多