androidkotlinbuttontextviewfindviewbyid

declare findViewById 'global'


I'm pretty new to android development with Kotlin and I want to declare Buttons and TextViews at the start of my program. So that I can use them in the entire program.

Now the following code works like intended, but as we can see, I have to use it two times and I want to avoid this.

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"
}

However if I move "var labelOutput: TextView = findViewById(R.id.textVIewOutput)" above "override fun onCreate" to make it 'global' and then try to start the app it just crashes.

So I'm not sure why and how this happens. Is this approach maybe completely wrong?


Solution

  • You should declare your TextView globally with

    var labelOutput: TextView? = null
    

    And then initialize it in your onCreate method with:

    labelOutput = findViewById(R.id.textVIewOutput)
    

    You can't initialize your views before the setContentView call set your current layout.

    To use your labelOutput instance just edit your outputSomethingfunction as

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