- An alert box with a single button
- A dialog box with two buttons
- A dialog box containing a list
- A dialog box containing checkboxes
Note:
- We will be using Android Platform 1.5 for developing our application.
To demonstrate how to create dialog boxes firstly we will be creating a basic application with four buttons and clicking on each of these buttons will display a different kind of dialog box. We will be using XML based layout for our Application's User Interface. Create a new Android project with the following properties -
- Project Name - DialogBox
- Name of the Application - Dialog Box
- Package name - com.botskool.DialogBox
- Activity Name - Dialog Box
There will be four buttons and a string as listed below -
- information string
- alert button (This button will be used to display an alert box)
- yesno button (This will be used to display a dialog box with Yes/No buttons)
- selectlist button (This will be used to display a dialog box which contains a list)
- selectlistwithcheckbox (This will be used to display a dialog box which contains a list along with checkbox)
Copy the following code in DialogBox.java -
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class DialogBox extends Activity implements OnClickListener{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** We need to set up a click listener on the alert button */
Button alert = (Button) findViewById(R.id.alertbutton);
alert.setOnClickListener(this);
/** We need to set up a click listener on the yesno button */
Button yesno = (Button) findViewById(R.id.yesnobutton);
yesno.setOnClickListener(this);
/** We need to set up a click listener on the selectlist button */
Button selectlist = (Button) findViewById(R.id.selectlist);
selectlist.setOnClickListener(this);
/** We need to set up a click listener on the selectlistwithcheckbox button */
Button selectlistwithcheckbox = (Button) findViewById(R.id.selectlistwithcheckbox);
selectlistwithcheckbox.setOnClickListener(this);
}
public void onClick(View view) {
/** check whether the alert button has been clicked */
if (view == findViewById(R.id.alertbutton)) {
// Code here to display alert box
}
/** check whether the yesno button has been clicked */
if (view == findViewById(R.id.yesnobutton)) {
// Code here to display the dialog box with Yes/No button
}
/** check whether the selectlist button has been clicked */
if (view == findViewById(R.id.selectlist)) {
//Code here to display the dialog box containing a list.
}
/** check whether the selectlistwithcheckbox button has been clicked */
if (view == findViewById(R.id.selectlistwithcheckbox)) {
//Code here to display the dialog box with checkbox
}
}
}
Copy the following code in main.xml -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/information"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Alert"
android:id="@+id/alertbutton"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Yes/No"
android:id="@+id/yesnobutton"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show List"
android:id="@+id/selectlist"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show List with Checkbox"
android:id="@+id/selectlistwithcheckbox"
/>
</LinearLayout>
Copy the following code in strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="information">Various kind of dialog boxes - by www.bOtskOOl.com</string>
<string name="app_name">Dialog Box</string>
</resources>
Compile and run the Android application and you will get this -
Now we need to write the code to create and display different dialog boxes. Let's start with the simple Alert box with single button. Copy the following code inside the if condition which checks whether the alert box has been clicked or not in the OnClick() function as shown below -
/** check whether the alert button has been clicked */
if (view == findViewById(R.id.alertbutton)) {
// Create the alert box
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
// Set the message to display
alertbox.setMessage("This is an alert box.");
// Add a neutral button to the alert box and assign a click listener
alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
// Click listener on the neutral button of alert box
public void onClick(DialogInterface arg0, int arg1) {
// The neutral button was clicked
Toast.makeText(getApplicationContext(), "'OK' button clicked", Toast.LENGTH_LONG).show();
}
});
// show the alert box
alertbox.show();
}
To create an Alert box we first use the AlertDialog.Builder subclass. We create an instance of this class with AlertDialog.Builder(Context) and then we set the different properties of alert box such as message and button to be displayed by using setMessage() and setNeutralButton()respectively. After this we display the alert box by using show() function.
setMessage() takes only one argument and that is the string to be displayed to the user. InsetNeutralButton() function the first argument is the name of the button.
Also we add a click listener to the (neutral) OK button by passing a function as second argument of setNeutralButton() function and we display a toast notification whenever this button is clicked/activated. Check out the screenshots below.
You must be wondering what a neutral button is? Well in Android we have three types of button -
- Positive or Yes
- Negative or No
- Neutral or Cancel
You can ONLY add one of each button type to your AlertDialog box. So this limits the number of possible buttons to three: positive, neutral, and negative. As quoted on Android website - These names are technically irrelevant to the actual functionality of your buttons, but should help you keep track of which one does what.
Now if we want to create a dialog box with two buttons you just need to use some other type of button apart from neutral button. Say for Yes/No dialog box we use a positive and a negative button then we can their property by calling setPostiveButton() and setNegativeButton() as shown below -
/** check whether the yesno button has been clicked */
if (view == findViewById(R.id.yesnobutton)) {
// Create the dialog box
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
// Set the message to display
alertbox.setMessage("This is a dialog box with two buttons");
// Set a positive/yes button and create a listener
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
// Click listener
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'Yes' button clicked", Toast.LENGTH_SHORT).show();
}
});
// Set a negative/no button and create a listener
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
// Click listener
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'No' button clicked", Toast.LENGTH_SHORT).show();
}
});
// display box
alertbox.show();
}
The functions setPostiveButton() and setNegativeButton() are similar to setNeutralButton(). Check out the screenshots below.
- A dialog box containing a list
- A dialog box containing checkboxes
Lets start with dialog box having a list in it. There is an onClick() function in the DialogBox.java. In this onClick() function we have a if condition to check whether Show List button has been clicked or not as shown below.
/** check whether the selectlist button has been clicked */
if (view == findViewById(R.id.selectlist)) {
//Code here to display the dialog box containing a list.
}
We will write our code inside this if condition to create and display the dialog box containing a list. For this we will use Builder sub-class of AlertDialog as we had in the previous two dialog boxes.
To create a list we will use setItem() method of this Builder sub class. The first argument of this setItem() function is an array containing the elements of the list that has to be created and the second argument is the click listener callback function that defines the action to take when the user selects an item. Check out the code given below -
/** check whether the selectlist button has been clicked */
if (view == findViewById(R.id.selectlist)) {
//List items
final CharSequence[] items = {"Milk", "Butter", "Cheese"};
//Prepare the list dialog box
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//Set its title
builder.setTitle("Pick an item");
//Set the list items and assign with the click listener
builder.setItems(items, new DialogInterface.OnClickListener() {
// Click listener
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
//display dialog box
alert.show();
}
On selecting a particular item the onClickListener() function will be called which in turn will display a toast notification containing the name of the selected item as shown in screenshots below.
Similarly for displaying a dialog box with checkboxes in it we use setSingleChoiceItems() method of the Builder sub class of AlertDialog. The first parameter of this method is again an array of items to be displayed. The second parameter is an integer value for the checkedItem, which indicates the zero-based list position of the default selected item and we use "-1" if don't want any item to be selected by default. The third parameter is the click listener function. Check outthe code given below -
/** check whether the selectlistwithcheckbox button has been clicked */
if (view == findViewById(R.id.selectlistwithcheckbox)) {
//List items
final CharSequence[] items = {"Milk", "Butter", "Cheese"};
//Prepare the list dialog box
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//Set its title
builder.setTitle("Pick an item");
//Set the list items along with checkbox and assign with the click listener
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
// Click listener
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
//If the Cheese item is chosen close the dialog box
if(items[item]=="Cheese")
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
//display dialog box
alert.show();
}
Check out the screenshots shown below.
In the onClickListener() function we have introduced an if condition which checks whether the selected item is Cheese and if it is so we have called a function dialog.dimiss(). This function closes/dismisses the dialog box. Apart from this everything is similar to the code of the previous dialog box i.e. whenever an item is selected the toast notification displays the selected item's name.
So now the complete code of DialogBox.java will be -
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class DialogBox extends Activity implements OnClickListener{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** We need to set up a click listener on the alert button */
Button alert = (Button) findViewById(R.id.alertbutton);
alert.setOnClickListener(this);
/** We need to set up a click listener on the yesno button */
Button yesno = (Button) findViewById(R.id.yesnobutton);
yesno.setOnClickListener(this);
/** We need to set up a click listener on the selectlist button */
Button selectlist = (Button) findViewById(R.id.selectlist);
selectlist.setOnClickListener(this);
/** We need to set up a click listener on the selectlistwithcheckbox button */
Button selectlistwithcheckbox = (Button) findViewById(R.id.selectlistwithcheckbox);
selectlistwithcheckbox.setOnClickListener(this);
}
public void onClick(View view) {
/** check whether the alert button has been clicked */
if (view == findViewById(R.id.alertbutton)) {
// Create the alert box
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
// Set the message to display
alertbox.setMessage("This is an alert box.");
// Add a neutral button to the alert box and assign a click listener
alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
// Click listener on the neutral button of alert box
public void onClick(DialogInterface arg0, int arg1) {
// The neutral button was clicked
Toast.makeText(getApplicationContext(), "'OK' button clicked", Toast.LENGTH_LONG).show();
}
});
// show the alert box
alertbox.show();
}
/** check whether the yesno button has been clicked */
if (view == findViewById(R.id.yesnobutton)) {
// Create the dialog box
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
// Set the message to display
alertbox.setMessage("This is a dialog box with two buttons");
// Set a positive/yes button and create a listener
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
// Click listener
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'Yes' button clicked", Toast.LENGTH_SHORT).show();
}
});
// Set a negative/no button and create a listener
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
// Click listener
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'No' button clicked", Toast.LENGTH_SHORT).show();
}
});
// display box
alertbox.show();
}
/** check whether the selectlist button has been clicked */
if (view == findViewById(R.id.selectlist)) {
//List items
final CharSequence[] items = {"Milk", "Butter", "Cheese"};
//Prepare the list dialog box
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//Set its title
builder.setTitle("Pick an item");
//Set the list items and assign with the click listener
builder.setItems(items, new DialogInterface.OnClickListener() {
// Click listener
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
//display dialog box
alert.show();
}
/** check whether the selectlistwithcheckbox button has been clicked */
if (view == findViewById(R.id.selectlistwithcheckbox)) {
//List items
final CharSequence[] items = {"Milk", "Butter", "Cheese"};
//Prepare the list dialog box
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//Set its title
builder.setTitle("Pick an item");
//Set the list items along with checkbox and assign with the click listener
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
// Click listener
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
//If the Cheese item is chosen close the dialog box
if(items[item]=="Cheese")
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
//display dialog box
alert.show();
}
}
}