Search code examples
androidandroid-alertdialogonbackpressed

Use onBackPressed with an alert dialog only for the main activity


I am with my first app and I'm using this method in the main activity:

Override
   public void onBackPressed () {
   new AlertDialog.Builder (this)
   .setIcon (android.R.drawable.ic_dialog_alert)
   .setTitle ("Closing Activity")
   .setMessage ("Are you sure you want to close this activity?")
   .setPositiveButton ("Yes", new DialogInterface.OnClickListener ()
   {
   Override
   public void onClick (DialogInterface dialog, int which) {
   Inicio.this.finish ();
   }

   })
   .setNegativeButton ("No", null)
   .show ();
   }

In this activity I go to other activities, the problem is that I want only appears when I leave the main activity (leave the application), but I alert appears when I leave any of the activities. I can not realize what is the solution, could someone help me? The method I wrote only in the main class.


Solution

  • Well this worked fine for me...

    @Override
    public void onBackPressed()
    {
    
        new AlertDialog.Builder (this)
           .setIcon (android.R.drawable.ic_dialog_alert)
           .setTitle ("Closing Activity")
           .setMessage ("Are you sure you want to close this activity?")
           .setPositiveButton ("Yes", new DialogInterface.OnClickListener ()
           {
               @Override
               public void onClick (DialogInterface dialog, int which) {
                   MainActivity.this.finish ();
               }
    
           })
           .setNegativeButton ("No", null)
           .show ();
    }
    

    Where MainActivity is my current activity... AND also, Where the other activities are not derived from the MainActivity.