【问题标题】:How do I initialize an array of buttons in Kotlin如何在 Kotlin 中初始化一组按钮
【发布时间】: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)

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

【问题讨论】:

  • 是的,如果您在类级别声明数组,它会抛出空指针,在本地执行或使用lateinitlazy,您应该在视图膨胀后初始化,在@987654327 之后进行活动@ 和 onViewCreated 中的片段。

标签: android arrays kotlin button


【解决方案1】:

您可能将代码放在错误的位置。您没有指定,但它要么在类本身中(在这种情况下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,这可能是您的问题。

【讨论】:

  • 是的,我把代码放在了课程的开头。将它放在 onCreate 函数中解决了它,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-12
  • 1970-01-01
  • 2020-03-13
  • 2011-11-19
  • 2016-08-22
相关资源
最近更新 更多