32
Android Application Development Training Tutorial For more info visit http://www.zybotech.in A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

How to Create a Dialog Box in Android - Part 2

Embed Size (px)

Citation preview

Page 1: How to Create a Dialog Box in Android - Part 2

Android Application Development Training Tutorial

For more info visit

http://www.zybotech.in

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 2: How to Create a Dialog Box in Android - Part 2

How to create a Dialog box in Android - Part 2

This is the second part of the How to a create a Dialog Box in Android tutorial. Follow this link - How to create a Dialog Box - Part 1, if you haven't read the first part and have directly landed here.

In this tutorial we will discuss the remaining two types of dialog boxes -

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

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 3: How to Create a Dialog Box in Android - Part 2

         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.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 4: How to Create a Dialog Box in Android - Part 2

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 5: How to Create a Dialog Box in Android - Part 2

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 6: How to Create a Dialog Box in Android - Part 2

 

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 out the code given below - 

 

/** check whether the selectlistwithcheckbox button has been clicked */

        if (view == findViewById(R.id.selectlistwithcheckbox)) {

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 7: How to Create a Dialog Box in Android - Part 2

         //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.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 8: How to Create a Dialog Box in Android - Part 2

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 9: How to Create a Dialog Box in Android - Part 2

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 10: How to Create a Dialog Box in Android - Part 2

 

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.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 11: How to Create a Dialog Box in Android - Part 2

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 12: How to Create a Dialog Box in Android - Part 2

 

So now the complete code of DialogBox.java will be -

package com.botskool.DialogBox;

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;

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 13: How to Create a Dialog Box in Android - Part 2

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

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 14: How to Create a Dialog Box in Android - Part 2

                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();

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 15: How to Create a Dialog Box in Android - Part 2

                }            });            AlertDialog alert = builder.create();            //display dialog box            alert.show();        }    }}

POST : Sample Code

AlertDialog.Builder builder = new AlertDialog.Builder(this); //DIALOG 1builder.setTitle("Title");builder.setMessage("Message ").setPositiveButton("OK", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int id) { //Some Processing}});builder.setNegativeButton("NAME BTN", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int id) { AlertDialog.Builder builder = new AlertDialog.Builder(context.this); // DIALOG 2builder.setTitle("TITLE");builder.setPositiveButton("BTN", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int id) {//Another Dialog //DIALOG 3}});builder.setItems(LIST, new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int item) {// SOME PROCESSING}});AlertDialog alert = builder.create();alert.show();}});builder.create().show();}

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 16: How to Create a Dialog Box in Android - Part 2

How to create a Dialog box in Android - Part 10 0diggsdigg

By Shashwat Srivastava

Hi again!  We are back with another tutorial on Android notifications. Make sure you go through the tutorial on Toast Notification before reading on.

In Android you can use a dialog box with one, two, or three buttons or none at all. You can also have a list of selectable items that consists of checkboxes or radio buttons.

For creating these dialog boxes we will be using AlertDialog which is an extension of Dialog class from Android API library. In this tutorial we will be creating four different types of dialog boxes -

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)

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 17: How to Create a Dialog Box in Android - Part 2

selectlistwithcheckbox (This will be used to display a dialog box which contains a list along with checkbox)

Copy the following code in DialogBox.java -

 

package com.botskool.DialogBox;

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 */

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 18: How to Create a Dialog Box in Android - Part 2

        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)) {

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 19: How to Create a Dialog Box in Android - Part 2

         //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 

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 20: How to Create a Dialog Box in Android - Part 2

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>

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 21: How to Create a Dialog Box in Android - Part 2

</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)) {

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 22: How to Create a Dialog Box in Android - Part 2

             // 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. In setNeutralButton() 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. 

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 23: How to Create a Dialog Box in Android - Part 2

 

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 24: How to Create a Dialog Box in Android - Part 2

 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 -

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 25: How to Create a Dialog Box in Android - Part 2

 

 /** 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();

        }

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 26: How to Create a Dialog Box in Android - Part 2

The functions setPostiveButton() and setNegativeButton() are similar to setNeutralButton(). Check out the screenshots below.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 27: How to Create a Dialog Box in Android - Part 2

 

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 28: How to Create a Dialog Box in Android - Part 2

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 29: How to Create a Dialog Box in Android - Part 2

 

 The rest of the two dialog boxes will be discussed in the second part of this tutorial. Follow this link - How to create a dialog box in Android - Part 2.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi