How to display a Yes/No dialog box in Android?

You can use alert box with Yes/No option for lots of reasons. I used this option to confirm if user wants to close my application.

Thus, when user clicks back while using my application i call show_alert() function:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
	if (keyCode == KeyEvent.KEYCODE_BACK) {
		show_alert();
		return true;
	}
	return super.onKeyDown(keyCode, event);
}

Now when show_alert is called:

private void show_alert() {
// TODO Auto-generated method stub
 AlertDialog.Builder alert_box=new AlertDialog.Builder(this);
 alert_box.setIcon(R.drawable.icon);
 alert_box.setMessage("Do you want to exit?");
 alert_box.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
 @Override
 public void onClick(DialogInterface dialog, int which) {
 // TODO Auto-generated method stub
		finish();
	}
 });

 alert_box.setNegativeButton("No", new DialogInterface.OnClickListener() {
 @Override
 public void onClick(DialogInterface dialog, int which) {
 // TODO Auto-generated method stub
 //Toast.makeText(getApplicationContext(), "No Button Clicked", Toast.LENGTH_LONG).show();
 }
 });

 alert_box.show();
}

You can do what ever you wish when Yes or No is clicked.

Keep checking for more updates.

Tags: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*