【发布时间】:2021-05-16 11:02:21
【问题描述】:
我是使用 Kotlin 进行 android 开发的新手,我想在我的程序开始时声明 Buttons 和 TextViews。这样我就可以在整个程序中使用它们。
现在下面的代码可以正常工作,但正如我们所见,我必须使用它两次,我想避免这种情况。
var labelOutput: TextView = findViewById(R.id.textVIewOutput)
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var useButton: Button = findViewById(R.id.buButton1)
var useButton2: Button = findViewById(R.id.buButton2)
var labelOutput: TextView = findViewById(R.id.textVIewOutput)
useButton.setOnClickListener{
labelOutput.setText(calc(3.0, 4.0).toString())
}
useButton2.setOnClickListener{
outputSomething()
}
}
private fun calc (a:Double, b:Double): Double {
val result = a + b
return result
}
private fun outputSomething (){
var labelOutput: TextView = findViewById(R.id.textVIewOutput)
labelOutput.text = "something"
}
但是,如果我将“var labelOutput: TextView = findViewById(R.id.textVIewOutput)”移到“override fun onCreate”上方以使其成为“全局”,然后尝试启动它刚刚崩溃的应用程序。
所以我不确定为什么以及如何发生这种情况。这种方法可能完全错误吗?
【问题讨论】:
标签: android kotlin button textview findviewbyid