How to implement the function "Click again to exit"?

some applications (for example, Dolphin HD Browser) implement the following function:

Pressing "Back" goes back to the back stack. When the initial view / activity / fragment is displayed and you press "Back", a symbol appears Toastsaying "Click" Back again to exit "or something similar.

How can I implement this feature?

+3
source share
3 answers

Catch the back-button event as follows:

public void onBackPressed() 
{
    //Add your logic here
    return;
}

Now create a flag so that your application does not close on first launch. Finally complete your activity by calling finish();in your activity.

For a quick show, Toasts use this:

Toast.makeText(this, "Press Back again to quit", Toast.LENGHT_SHORT).show();

, . , this.

+2

:

  int count = 0; 

:

public void onBackPressed() 
{
   if(count == 1)
   {
      count=0;
      finish();
   }
   else
   {
      Toast.makeText(getApplicationContext(), "Press Back again to quit.", Toast.LENGTH_SHORT).show();
      count++;
   }

    return;
}
+8

For API level 1, cancels the action

public boolean onKeyDown(int keyCode, KeyEvent event) {
  if (keyCode == KeyEvent.KEYCODE_BACK) {
    ....

For API level 5 and above, see what Pieter888 said.

+2
source

All Articles