Create AlertDialog 2 – Android

Home / Android / Create AlertDialog 2 – Android

This post is in the connection with the previous post about creating AlertDialog. In this demo application an AlertDialog is created with two buttons, i.e. OK and Cancel. There is some modifications in the MainActivity.java code of previous code.

1. AlertDialog to display information

2. To display and get confirmation from the user

In order to get confirmation (yes/no situation) user should have two types of buttons, i.e. one to accept and another to reject. In this demo application those buttons are named as OK and Cancel. The name varies as per the situation, and so does the functionality. Here, only Toast message is being displayed. But, it can be modified to add more functionalities to these buttons, viz. calling another activity (passing Intent), going back to the previous activity (finishing the current activity), can be used to ask user if they want to exit the application, etc.




activity_main.xml



    

MainActivity.java

alert.setCancelable(false); is required, if you need your user to cancel the dialog only when they click on either of the buttons.

package com.pcsalt.example.alertdialogdemo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	Button btnAlertDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		btnAlertDialog = (Button) findViewById(R.id.btn_AlertDialog);
		
		btnAlertDialog.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				displayAlertDialog();
			}
		});
	}
	
	public void displayAlertDialog() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Confirm");
		alert.setMessage("Are you sure, you want to exit?");
		alert.setCancelable(false);
		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Toast.makeText(getBaseContext(), "Cancel clicked", Toast.LENGTH_SHORT).show();
			}
		});
		
		alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Toast.makeText(getBaseContext(), "OK clicked", Toast.LENGTH_SHORT).show();
			}
		});
		AlertDialog dialog = alert.create();
		dialog.show();
	}
}

Screenshot

AlertDialog21 AlertDialog22 AlertDialog23 AlertDialog24

Download source:

3. To display a formatted layout with some components like EditText, CheckBox, etc.