如何在Kotlin中使用getResources()设置Button的文本?

时间:2018-11-21 20:02:31

标签: android kotlin

我正在尝试使用getResources()和getIdentifier()识别按钮,然后为其设置文本。下面的代码显示了我认为它应该如何工作(只需设置对象的ID和文本)。

while (c < 65) {
    val resID = getResources().getIdentifier("S1", "id", getPackageName())
    resID.text = ""
}

相反,我得到一个错误,“。text”显示为红色。我应该如何进行设置以按预期运行。

3 个答案:

答案 0 :(得分:2)

resIDButton“命名” S1的整数ID。
用它来找到Button

val resID = resources.getIdentifier("S1", "id", getPackageName())
val button = findViewById<Button>(resID)
button.text = ""

答案 1 :(得分:1)

基于Docs的getIdentifier返回Int,因此您需要findViewById并使用getIdentifier结果才能使用该对象

答案 2 :(得分:-1)

如果引用的int并非来自 R.id,则无法使用Kotlin扩展。

  1. 按钮是一个视图,然后您可以使用来访问它 findViewById<Button>(buttonId)

  2. 如果您要从资源中检索ID,只需getResources().getIdentifier("S1", "id", getPackageName())

最后,您将看到这样的情况:

val buttonId = getResources().getIdentifier("S1", "id", getPackageName())
val button = findViewById<Button>(buttonId)
button.setText("")