'How to trigger setOnClickListener on second consecutive press of the same button
so I have this setOnClickListener in my MainActivity.kt and I was wondering how I could upgrade it to set an integer in my code to 1 when the button is pressed two consecutive times
this is my setOnClickListener right now:
reset.setOnClickListener{
sum = 1
Toast.makeText(applicationContext,"enter the number again",Toast.LENGTH_LONG).show()
stevec.getText().clear()
sumText.setText("" + sum)
}
Solution 1:[1]
why don't you use a counter to keep track of your click?. Something like this
var counter= 0
reset.setOnClickListener{
counter +=1
if(counter==2){
// do your work
counter=0
}
}
Now set the initial counter to 0 in case of the press of any other button.. you can also use a boolean in the form var hasResetBeenClickedOnce=false. The logic is the same
otherbutton.setOnClickListener{
counter=0
}
Solution 2:[2]
var i =0
reset.setOnClickListener{
if(i=0){
i=1
}
else{
sum = 1
Toast.makeText(applicationContext,"enter the number again",Toast.LENGTH_LONG).show()
stevec.getText().clear()
sumText.setText("" + sum)
i=0
}
}
There are multiple ways to achieve this.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | pak |
