0

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

2 Answers2

0
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.

pak
  • 55
  • 5
0

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
}
Narendra_Nath
  • 4,578
  • 3
  • 13
  • 31
  • would work, but not in my case since the button needs to be clicked two times consecutively, is there a way to track if any other button was clicked before reset button was clicked second time so I can set counter = 0 if any other button was clicked and just keep reseting the counter until the button is clicked two times in a row – Anze Ludvik Mar 24 '22 at 17:48
  • Updated the answer .> let me know if you face any more issues – Narendra_Nath Mar 24 '22 at 17:51
  • damn didn't even think about doing it like that...It works now the way it should thank you for your help! – Anze Ludvik Mar 24 '22 at 18:28
  • Happy to help. do accept the answer if you found it useful. Welcome toStackOverflow' – Narendra_Nath Mar 24 '22 at 18:54