How to show a alert dialog after pressing a back button in android studio with source code

 How to show an alert dialog with an icon when clicking on the back press button in android studio

showing alert dialog when a user pressing the back button.

We will use icon and background color to display an awesome alert dialog box.

I am going to show you how to show the alert dialog box when the user presses the back button.

Android studio creating alert dialog when back button is press

When a user clicks on back then a dialog shows and displays a message like 'do you want to exit or do you really want to exit?'

Given two colorful button 'YES' or 'NO'

If the user clicks on the 'YES' button then the user exit the application.

If the user clicks on the 'NO' button then the user, not exit.

The first alert dialog will show, the latter will be


Alert Dialog with Icon


the exit in an android.


Watch Video

https://youtu.be/Sn1inVJcS9s


Alert dialog after exit






public void onBackPressed() {
        AlertDialog.Builder builder=new AlertDialog.Builder ( this );
        AlertDialog.Builder builder1=new AlertDialog.Builder ( this,R.style.AlertDialogTheme );

        builder.setTitle ( "NewEra Resume Builder" );
        builder.setIcon ( R.drawable.logoround );
        builder.setMessage ( "Do You want To Exit?" )

                .setCancelable ( false )
                .setPositiveButton ( "YES", new DialogInterface.OnClickListener () {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        finish ();
                    }
                } )
                .setNegativeButton ( "NO", new DialogInterface.OnClickListener ()

                {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel ();

                    }
                } );
        AlertDialog alertDialog=builder.create ();
        alertDialog.show ();
        alertDialog.getButton ( AlertDialog.BUTTON_POSITIVE ).setBackgroundColor ( getResources ().getColor ( R.color.white ) );
        alertDialog.getButton ( AlertDialog.BUTTON_NEGATIVE ).setBackgroundColor ( getResources ().getColor ( R.color.black ) );
       // alertDialog.getWindow ().setLayout ( 1200,600 );
 int width=(int)(getResources ().getDisplayMetrics ().widthPixels*0.90);
        int heigt=(int)(getResources ().getDisplayMetrics ().heightPixels*0.25);
        alertDialog.getWindow ().setLayout ( width,heigt );

        alertDialog.getWindow ().setBackgroundDrawableResource ( R.drawable.alertdialoggradient );
    }
إرسال تعليق (0)
أحدث أقدم