• Register
  • Log in
  • Home
  • Contact

Android Dialog and AlertDialog Example



A Dialog is a small that popup in front of main view, to make a user decision/action or enter additional information. In the example below we will show you how to create AlertDialog and Customise Dialog.
//AlertDialog
        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        //Set Custom view
        //LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //View view = inflater.inflate(R.layout.yourView, null);
        //builder.setView(view);
        //Set Message
        alertDialog.setMessage("Would to like to delete this file?");
        
        //Customise Title
        TextView title = new TextView(this);
        title.setText("Alert Dialog");
        title.setBackgroundColor(Color.DKGRAY);
        title.setPadding(10, 10, 10, 10);
        title.setGravity(Gravity.CENTER);
        title.setTextColor(Color.WHITE);
        title.setTextSize(20);
        alertDialog.setCustomTitle(title);
        
        //Dialog Positive and negative buttons
        alertDialog.setPositiveButton(android.R.string.ok,new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   // User clicked OK button
               }
           });
        alertDialog.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   // User cancelled the dialog
               }
           });
    
 

//Dialog
        final Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.dialogview);
        TextView titleView = (TextView) dialog.findViewById(android.R.id.title);
        if(titleView != null) {
            titleView.setGravity(Gravity.CENTER);
            titleView.setTextColor(Color.WHITE);
            titleView.setTextSize(24);
            titleView.setTypeface(Typeface.DEFAULT_BOLD);
        }
        Window window = dialog.getWindow();
        window.setLayout(200, 100);
        dialog.setTitle("Choose One");
        dialog.setCancelable(true);

 


© 2021 - KodeCenter beta