首页 > 解决方案 > 如何在 Kotlin 中初始化一组按钮

问题描述

我想直接初始化一个按钮数组,而不必指定变量名。我以为我在这里找到了答案:Array of buttons in Kotlin,但答案抛出了 NullPointerException。我还在谷歌搜索“kotlin 中的按钮数组”,但我发现的唯一相关信息来自我链接的问题。

我用了

val intervalButtons = arrayOf(
        findViewById<Button>(R.id.set30secButton),
        findViewById<Button>(R.id.set60secButton),
        findViewById<Button>(R.id.set90secButton),
        findViewById<Button>(R.id.set120secButton)
    )

但是我也尝试在 build.gradle 文件中应用 plugin: 'kotlin-android-extensions' 并使用

val intervalButtons = arrayOf(set30secButton, set60secButton, set90secButton, set120secButton)

但这仍然会引发 NullPointerException。

如果我使用

        btn1 = findViewById<Button>(R.id.set30secButton)

它就像一个魅力,但就像我说的,如果我不需要,我不想指定每个变量名。

标签: androidarrayskotlinbutton

解决方案


您可能将代码放在错误的位置。您没有指定,但它要么在类本身中(在这种情况下findViewById很可能返回 null),要么在onCreate- 在这种情况下它在此函数之外不可见

无论哪种方式,正确的方法是:

...
private lateinit var intervalButtons: Array<Button>
...
override fun onCreate(savedInstanceState: Bundle?) {
    setContentView(R.layout.your_view) // <- this is important, must be before     findViewById
    intervalButtons = arrayOf(
        findViewById<Button>(R.id.set30secButton),
        findViewById<Button>(R.id.set60secButton),
        findViewById<Button>(R.id.set90secButton),
        findViewById<Button>(R.id.set120secButton)
    )
    ...
}

lateinit var意味着变量将在稍后初始化,因此不需要立即初始化

或者像这样:

val intervalButtons: Array<Button> by lazy {
    arrayOf(
        findViewById<Button>(R.id.set30secButton),
        findViewById<Button>(R.id.set60secButton),
        findViewById<Button>(R.id.set90secButton),
        findViewById<Button>(R.id.set120secButton)
    )
}
...
override fun onCreate...

by lazy意味着该变量intervalButtons仅在需要时才会被初始化——就像当您尝试访问其中一个按钮时一样。在这两种解决方案findViewById中都调用after setContentView,这可能是您的问题。


推荐阅读