【发布时间】:2021-04-24 23:30:56
【问题描述】:
我想直接初始化一个按钮数组,而不必指定变量名。我以为我在这里找到了答案: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)
它就像一个魅力,但就像我说的,如果我不需要,我不想指定每个变量名。
【问题讨论】:
-
是的,如果您在类级别声明数组,它会抛出空指针,在本地执行或使用
lateinit或lazy,您应该在视图膨胀后初始化,在@987654327 之后进行活动@ 和onViewCreated中的片段。
标签: android arrays kotlin button