Android Popup box/Dialog box code example - Java

When Developing an Android application, sometimes you want to have confirmation on the action done by the user. Using a popup box or dialog box will help to get the user's intention on what are they doing. 

Here is the sample code to use the popup box/dialog box to show a message to the user. 

Full Code example.

 import androidx.appcompat.app.AlertDialog;  
 import androidx.appcompat.app.AppCompatActivity;  
 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);  
   }  
   @Override  
   public void onBackPressed(){  
     ShowMessageExit("Are You Sure You Want To Quit?");  
   }  
   private void ShowMessageExit(String Message){  
     new AlertDialog.Builder(this)  
         .setMessage(Message)  
         .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {  
           public void onClick(DialogInterface dialog, int which) {  
             android.os.Process.killProcess(android.os.Process.myPid());  
             System.exit(0);  
           }  
         })  
         .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {  
           public void onClick(DialogInterface dialog, int which) {  
             // do nothing  
           }  
         })  
         .setIcon(android.R.drawable.ic_dialog_alert)  
         .show();  
   }  

Output.


User getting confirmation once clicks back button in the navigation panel.



Popular posts from this blog

Example to disable save as certain file type in SSRS Report Viewer

How to create DataGrid or GridView in JSP - Servlet

Control Webpart Visible/Enable using macro in Kentico