I have an Activity to exit from which I need to implement a double click.

User clicks once and pops up an informational pop-up , but if user clicks 2 times, then the standard onBackPeressed() should execute.

Pop-up is, I can not only guess how to properly describe the condition of pressing ... Only ideas come through that head ...

  • 2
    This two years ago was googled for 2 minutes. - Yuriy SPb

4 answers 4

 int backPressedQ = 0; @Override public void onBackPressed() { Log.d(LOG, "onBackPressed"); if (this.backPressedQ == 1) { this.backPressedQ = 0; super.onBackPressed(); } else { this.backPressedQ++; Toast.makeText(this, "Нажмите ещё раз, чтобы выйти", Toast.LENGTH_SHORT).show(); } //Обнуление счётчика через 5 секунд final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { // Do something after 5s = 5000ms backPressedQ = 0; //checkNew(); } }, 5000); } 

    Add a counter, for example, on odd pop values ​​on even onBackPeressed (). uses operator (%)

     int counter = 0; @Override public void onClick(DialogInterface dialog, int which) { counter++; if(counter%2 != 0){ //popup }else { onBackPressed(); } } 
    • I wonder why someone has a minus - Android Android
    • It is more logical to use a Boolean variable in such a construction and invert it. Also in the question you need a reaction to the system button back, and not to the user button. - pavlofff
    • Yes, I did not take into account some subtleties, but I just wanted to show a person a concept that will help solve his problem. - Eugene Troyanskii 1:27 pm

    Try this

     private static final int TIME_INTERVAL = 2000; private long mBackPressed; @Override public void onBackPressed(){ if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) { super.onBackPressed(); return; } else { //popup } mBackPressed = System.currentTimeMillis(); } 
       boolean doubleClick = false; 

      At the click:

       if(!doubleClick){ doubleClick = true; } else{ // Ваши действия doubleClick = false; } 

      on svaypah and other tangencies that are not related to a click, just hang doubleClick = false;

      You can add a timer to set the flag to false if necessary. But the latter is no longer necessary, especially for the handler on one particular control.

      Although, in your case, it is with the timer that the solution will turn out. If, let's say, once a second, check the status of the flag “there was a click” and the flag “there was a double tap” and call the appropriate actions.

      Or start the timer at the first click and stop it if the desired condition is not met - until the next event.

      • one
        instead of a double conditional operator, the simplest doubleClick = !doubleClick - invert the state to the opposite, and the condition is simplified to if(doubleClick){ // действие } - pavlofff