android - 如何在 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)
它就像一个魅力,但就像我说的,如果我不需要,我不想指定每个变量名。
解决方案
您可能将代码放在错误的位置。您没有指定,但它要么在类本身中(在这种情况下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
,这可能是您的问题。
推荐阅读
- python - Python 无法通过将文件夹名称设置为输入来创建子文件夹
- python - 我只能打印 e[i] 而没有别的。即使我注释掉该行,它仍然会被打印出来,但没有其他打印调用起作用
- javascript - Typescript tapAsync 函数无法设置正确的类型
- c# - 在特定情况下,LinkLabel 宽度不够
- email - 与 office365 的 SMTP 连接延迟
- javascript - 错误类型 -parseerror 和状态码 - 200 发生错误
- python - 如何在 Firefox Webdriver 中永久设置代理
- svg - 如何在 SVG 的 Gnuplot 中鼠标悬停时显示值?
- python - 基于云的计费软件的数据库结构,规划问题
- perl - 获取错误错误消息:在 te_analysis/transposonPSI_result_2fasta.pl 行的模式匹配 (m//) 中使用未初始化的值 $_