How to show alert dialog when clicking on the back press button in android studio
In this post, I am going to show you how to show the alert dialog box when the user presses the back button.
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.
The first alert dialog will show, the latter will be the exit in an android.
activity_main.xml<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
package com.example.alertdialog; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate ( savedInstanceState ); setContentView ( R.layout.activity_main ); } @SuppressLint("ResourceAsColor") public void onBackPressed(){ AlertDialog.Builder builder=new AlertDialog.Builder ( this ); builder.setTitle ( "New simple Alert dialog" ); builder.setIcon ( R.drawable.ic_exit_to_app_black_24dp ); builder.setMessage ( "Do you realy wnat to exit?" ) .setCancelable ( false ) .setPositiveButton ( "Yes", new DialogInterface.OnClickListener () { @Override public void onClick(DialogInterface dialog, int which) { finish (); } } ) .setNegativeButton ( "no", new DialogInterface.OnClickListener () { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel (); } } ); AlertDialog alertDialog=builder.create (); alertDialog.show (); alertDialog.getButton ( AlertDialog.BUTTON_POSITIVE ).setBackgroundColor ( getResources ().getColor ( R.color.green) ); alertDialog.getButton ( AlertDialog.BUTTON_NEGATIVE ).setBackgroundColor ( getResources ().getColor ( R.color.red) ); //SET HEIGHT AND WIDTH OF ALERT DIALOG BOX int width=(int)(getResources ().getDisplayMetrics ().widthPixels*0.85); int height=(int)(getResources ().getDisplayMetrics ().heightPixels*0.30); alertDialog.getWindow ().setLayout ( width,height ); alertDialog.getWindow ().setBackgroundDrawableResource ( R.drawable.ic_launcher_background ); } }
https://youtu.be/VAvtYh_Dwdg
SUBSCRIBE to downloadDownload Source code