Working With AlertDialogbox Android- UI Widget

AlertDialogBox

As per the name suggests Alert Dialog Box is same as other programming language . It shows or prompt user that so you really want to exit this application or similar things. Lets Explore – Download Code

1). First of all create new project and in activity_main.xml file their is nothing special but if you want to develop something interesting app then you can customize by your own like on back button press Alert dialog box etc.

2). MainActivity.java , I include AlertDialog.Builder class and via its object I set Message , Title and other properties like  two buttons namely yes or no etc .

MainActivity.java 

package androidarena.alertdialog;

import androidarena.alertdialog.R;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);
		
		builder.setMessage("Do you want to close this app ?")
		    .setCancelable(false)
		    .setPositiveButton("Yeah !", new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int id) {
		    finish();
		    }
		    })
		    .setNegativeButton("No way", new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int id) {
		    //  Action for 'NO' Button
		    dialog.cancel();
		}
		    });
		
		AlertDialog alert = builder.create();
		 alert.setTitle("Alert-BOX");
		 alert.show();
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}

Output – alertdialogboxAny query or customization on this tutorial , feel free to share . Happy Coding :p

Leave a Reply

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