Home > other >  How to trigger setOnClickListener on second consecutive press of the same button
How to trigger setOnClickListener on second consecutive press of the same button

Time:03-25

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

CodePudding user response:

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.

CodePudding user response:

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
}
  • Related