Home > Enterprise >  Kotlin button listener
Kotlin button listener

Time:05-29

I want to increase the value of i every time the button is clicked

I've tried this code but it's not working.

val textview = findViewById<TextView>(R.id.texttest)
    var i = 10

        bookbutton.setOnClickListener {

            i  
        }

    textview.text = "$i"

CodePudding user response:

You have to set the text inside the listener:

bookbutton.setOnClickListener {
    i  
    textview.text = "$i"
}

CodePudding user response:

Your listener is updating the value of i — but that's not having any visible effect because by then it's too late: the text shown in your textview has already been set.

Let's review the order of events:

  • Your code runs. That creates a text view and a variable, sets a listener on the button, and sets the text in the text view.

  • At some later point(s), the user might click on the button. That calls the listener, which updates the variable.

So while your code sets the listener, the listener does not run until later. It might not run at all, or it might run many times, depending on what the user does, but it won't run before you set the text in the text view.

So you need some way to update the text when you update the variable. The simplest way is to do explicitly it in the listener, e.g.:

bookbutton.setOnClickListener {
    textview.text = "${  i}"
}

(There are other ways — for example, some UI frameworks provide ways to ‘bind’ variables to screen fields so that this sort of update happens automatically. But they tend to be a lot more complex; there's nothing wrong with the simple solution.)

  • Related