Select 多个 kotlin 按钮并在 findViewById() 中使用变量 - android studio

Select buttons more than one kotlin and using variables in findViewById() - android studio

我想用 9 个按钮执行操作 buttons.Is 无论如何,一次用 9 个按钮执行操作,而不是一个接一个。 如果我可以将变量添加到 findViewById() 我会解决问题。 例如,我想一次 select 9 个按钮(使用 for 循环),如下所示

for(i in 1..9){
   findViewById(R.id.button+i).text="New Text"
}

此方法无效,请提出最佳方法。

我想要这样的 javascript 等价物: document.getElementById("button"+i)

在您的 activity 中声明:

var buttons: ArrayList<Button> = arrayListOf()

并在 onCreate() 中:

    for (i in 1..100) {
        buttons.add(findViewById<Button>(resources.getIdentifier("button" + i, "id", this.getPackageName())))
    }

现在您的所有按钮都在一个列表中。

如果您想更改按钮的状态,请说全部禁用它们:

buttons.forEach { it.isEnabled = false }

您可以为每个按钮(如 button1、button2 等)设置标签并执行类似操作

for(i in 1..9){
   (view.findViewWithTag("button"+i.toString()) as Button).text = "New Text"
}