【问题标题】:declare findViewById 'global'声明 findViewById 'global'
【发布时间】: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


    【解决方案1】:

    您应该使用全局声明您的 TextView

    var labelOutput: TextView? = null
    

    然后在你的onCreate 方法中初始化它:

    labelOutput = findViewById(R.id.textVIewOutput)
    

    setContentView 调用设置您的当前布局之前,您无法初始化您的视图。

    要使用您的 labelOutput 实例,只需将您的 outputSomethingfunction 编辑为

    private fun outputSomething (){
        labelOutput?.text = "something"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      • 1970-01-01
      • 1970-01-01
      • 2016-07-10
      • 1970-01-01
      • 1970-01-01
      • 2015-10-19
      相关资源
      最近更新 更多