SlideShare a Scribd company logo
Android Application Development Training Tutorial




                      For more info visit

                   http://www.zybotech.in




        A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Android Basics – Dialogs and Floating Activities
As we know android provide Activity class for developing application screens. But many a time application
needs to show Dialog boxes or floating screen to do simple tasks likes taking input from user or ask for
confirmation etc.

In android Dialogs can be created in following 2 ways:

1. Creating a dialog with the help of android Dialog class or its subclass like AlertDialog.
2. Using dialog theme for the activity.

Using android Dialog class:
Let see how we can create a dialog with the help of Dialog class. To define a dialog the dialog class has to
extend the android Dialog class.

class MyDialog extends Dialog {
/**
* @param context
*/
public MyDialog(Context context) {
super(context);
}
}

Define a layout for our dialog. Here is the xml file for of the layout that asks for user’s name.

<?xml version=”1.0″ encoding=”utf-8″?>


<LinearLayout
android:id="@+id/widget28"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:id="@+id/nameMessage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Enter Name:"
>
</TextView>
<EditText
android:id="@+id/nameEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
>
</EditText>
<LinearLayout


                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
android:id="@+id/buttonLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
>
<Button
android:id="@+id/okButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK"
>
</Button>
<Button
android:id="@+id/cancelButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
>
</Button>
</LinearLayout>
</LinearLayout>

Use the above layout for our dialog

class MyDialog extends Dialog {
....

/**

* @see android.app.Dialog#onCreate(android.os.Bundle)

*/

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

Log.d("TestApp", "Dialog created");

setContentView(R.layout.mydialog);

}

}

Now the dialog can be shown by calling the show method like this

…

MyDialog dialog = new MyDialog(context);
dialog.show();

…


                           A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Event handling for the Dialog controls are same as in case of the activity. Modify the dialog code to handle the
onclick event on the ok and cancel button.

class MyDialog extends Dialog implements OnClickListener {

private Button                 okButton;

private Button                 cancelButton;

private EditText               nameEditText;

protected void onCreate(Bundle savedInstanceState) {

okButton = (Button) findViewById(R.id.okButton);

cancelButton = (Button) findViewById(R.id.cancelButton);

nameEditText = (EditText) findViewById(R.id.nameEditText);

okButton.setOnClickListener(this);

cancelButton.setOnClickListener(this);

}




public void onClick(View view) {

switch (view.getId()) {

case R.id.okButton:

dismiss();

break;

case R.id.cancelButton:

cancel();

break;

}

}

}

To close the dialog the dismiss() method can be called. The dialog can call the dismiss method itself or some
other code can also close the dialog by calling dismiss().




                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
The dialog also supports cancel. Canceling means the dialog action is canceled and does not need to perform
any operation. Dialog can be canceled by calling cancel() method. Canceling the dialog also dismisses the
dialog.

When user clicks the phones BACK button the dialog gets canceled. If you do not want to cancel the dialog on
BACK button you can set cancelable to false as

setCancelable(false);

Note that the cancel() method call till be able to cancel the dialog (which is the desirable functionality in most
cases). The dialog’s cancel and dismiss events can be listened with the help of OnCancelListener and
OnDismissListener.

Returning information from dialog:
Now our dialog can take the name from the user. We need to pass that name to the calling activity. Dialog class
does not provide any direct method for returning values. But our own Listener can be created as follows:

public interface MyDialogListener {

public void onOkClick(String name); // User name is provided here.

public void onCancelClick();

}

The dialog’s constructor has to be modified to take the object of the listener:

public MyDialog(Context context, MyDialogListener listener) {
super(context);
this.listener = listener;
}

Now the calling activity needs to provide the object of the class that implements the MyDialogListener which
will gets called on ok or cancel button clicks.

Now we need update the onclick method to return the user name.

public void onClick(View view) {
switch (view.getId()) {
case R.id.okButton:
listener.onOkClick(nameEditText.getText().toString()); // returning the user's name.
dismiss();
break;
case R.id.cancelButton:
cancel();
break;
}
}

Using AlertDialog:

AlertDialog is the subclass of the Dialog. It by default provide 3 buttons and text message. The buttons can be
made visible as required. Following code creates an AlertDialog that ask user a question and provide Yes, No
option.
                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
AlertDialog dialog = new AlertDialog.Builder(context).create();

dialog.setMessage("Do you play cricket?");

dialog.setButton("Yes", myOnClickListener);

dialog.setButton2("No", myOnClickListener);

dialog.show();

The onClick method code for the button listener myOnClickListener will be like this:

public void onClick(DialogInterface dialog, int i) {
switch (i) {
case AlertDialog.BUTTON1:
/* Button1 is clicked. Do something */
break;
case AlertDialog.BUTTON2:
/* Button2 is clicked. Do something */
break;
}
}

AlertDialog.Builder:
AlertDialog has a nested class called ‘Builder’. Builder class provides facility to add multichoice or single
choice lists. The class also provides methods to set the appropriate Adaptors for the lists, set event handlers for
the list events etc. The Builder button calls the Button1, Button2, Button3 as PositiveButton, NeutralButton,
NegativeButton.

Here is an example of dialog box with Multichoice list

new AlertDialog.Builder(context)
.setIcon(R.drawable.icon)
.setTitle(R.string.alert_dialog_multi_choice)
.setMultiChoiceItems(R.array.select_dialog_items,
new boolean[]{false, true, false, true, false},
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) {
/* Something on click of the check box */
}
})
.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {

/* User clicked Yes so do some stuff */

}

})

.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int whichButton) {

/* User clicked No so do some stuff */



                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
}

})

.create();

Activity Managed Dialog:

Android also provide facility to create dialogs. Activity created dialog can be managed by Activity methods
like showDialog(), onCreateDialog(), onPrepareDialog(), dismissDialog(), removeDialog().
The onCreateDialog create the dialog that needs to be shown, for example

/**
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id) {
return new AlertDialog.Builder(this).setMessage("How are you?").setPositiveButton("Fine",
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

/* Do something here */

}

}).setNegativeButton("Not so good", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

/* Do something here */

}

}).create();

}

You can create multiple dialog boxes and differentiate them with the id parameter. The dialog can be shown
with the help of showDialog(id) method. The onCreateDialog method gets called for the first time when
showDialog method is called. For subsequent calls to the showDialog() the dialog is not created but shown
directly.
If you need to update the dialog before it is getting shown then you can do that in onPrepareDialog() method.
The methods get called just before the dialog is shown to the user.
To close the dialog you can call dismissDialog() method. Generally you will dismiss the dialogs in the click
handles of the dialog buttons.
The removeDialog() method will remove the dialog from the activity management and if showDialog is again
called for that dialog, the dialog needs to be created.

Using android Dialog theme for activity:
Another simple way to show the dialog is to make the Activity to work as a Dialog (floating activity). This can
be done by applying dialog Theme while defining the activity entry in the AndroidManifest.xml


                           A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
<activity android:name=”.DialogActivity” android:label=”@string/activity_dialog”
android:theme=”@android:style/Theme.Dialog”>
…
</activity>

The activity will be shown as a dialog as the activity is using ‘Theme.Dialog’ as theme.




                           A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

More Related Content

What's hot (7)

PDF
Swingpre 150616004959-lva1-app6892
renuka gavli
 
PDF
JAVA GUI PART I
OXUS 20
 
PDF
Java GUI PART II
OXUS 20
 
PPT
25 awt
degestive
 
PPTX
GUI programming
Vineeta Garg
 
PDF
swingbasics
Arjun Shanka
 
PDF
UITableView Pain Points
Ken Auer
 
Swingpre 150616004959-lva1-app6892
renuka gavli
 
JAVA GUI PART I
OXUS 20
 
Java GUI PART II
OXUS 20
 
25 awt
degestive
 
GUI programming
Vineeta Garg
 
swingbasics
Arjun Shanka
 
UITableView Pain Points
Ken Auer
 

Viewers also liked (9)

PPT
Интересно о крокодилах
chely111chely
 
DOCX
SA’EY
Hafiz Amir Aslam
 
PPTX
Music Video Analysis
CallumHiggins
 
PPTX
Personalisation for ecommerce
panarin
 
DOC
Nc trabajo
Naysha Shirley
 
PPT
Ah manifest destiny ch 12
cmonafu
 
DOCX
Impact auto comp
Khusro Chishty
 
PPTX
Creating a logo
CallumHiggins
 
PPTX
AMERICAN HISTORY Ch.2 Part 1
cmonafu
 
Интересно о крокодилах
chely111chely
 
Music Video Analysis
CallumHiggins
 
Personalisation for ecommerce
panarin
 
Nc trabajo
Naysha Shirley
 
Ah manifest destiny ch 12
cmonafu
 
Impact auto comp
Khusro Chishty
 
Creating a logo
CallumHiggins
 
AMERICAN HISTORY Ch.2 Part 1
cmonafu
 
Ad

Similar to Android basics – dialogs and floating activities (20)

PPTX
Alert Dialog Box in Android for mca students
TheRockyFF
 
PPTX
Android Lab Test : Creating a dialog Yes/No (english)
Bruno Delb
 
PDF
Android ui dialog
Krazy Koder
 
PPTX
MAD_lecture-DialogBoxesrejgjgjgkhkhkhk.pptx
himanshunanobhatt
 
PPT
Progress Dialog, AlertDialog, CustomDialog
Sourabh Sahu
 
PPTX
Android Dialogs Tutorial
Perfect APK
 
PPTX
Android Dialogs Tutorial
Perfect APK
 
PDF
Android session 3
Ahesanali Suthar
 
PPTX
Lecture 7: Android Kinds of Dialogs.pptx
Yousef Alamir
 
PDF
Android basic 3 Dialogs
Eakapong Kattiya
 
DOCX
Android-dialogs in android-chapter14
Dr. Ramkumar Lakshminarayanan
 
PPT
Android Bootcamp Tanzania:understanding ui in_android
Denis Minja
 
PDF
Mobile Application Development -Lecture 09 & 10.pdf
AbdullahMunir32
 
PDF
Android App Development 03 : Widget &amp; UI
Anuchit Chalothorn
 
PPTX
07.3. Android Alert message, List, Dropdown, and Auto Complete
Oum Saokosal
 
ODP
Android App Development - 11 Lists, grids, adapters, dialogs and toasts
Diego Grancini
 
PPT
"Android" mobilių programėlių kūrimo įvadas #2
Tadas Jurelevičius
 
PPT
Android app development
Vara Prasad Kanakam
 
PPTX
Android App Development (Basics)
Alberto Rubalcaba Stockman
 
Alert Dialog Box in Android for mca students
TheRockyFF
 
Android Lab Test : Creating a dialog Yes/No (english)
Bruno Delb
 
Android ui dialog
Krazy Koder
 
MAD_lecture-DialogBoxesrejgjgjgkhkhkhk.pptx
himanshunanobhatt
 
Progress Dialog, AlertDialog, CustomDialog
Sourabh Sahu
 
Android Dialogs Tutorial
Perfect APK
 
Android Dialogs Tutorial
Perfect APK
 
Android session 3
Ahesanali Suthar
 
Lecture 7: Android Kinds of Dialogs.pptx
Yousef Alamir
 
Android basic 3 Dialogs
Eakapong Kattiya
 
Android-dialogs in android-chapter14
Dr. Ramkumar Lakshminarayanan
 
Android Bootcamp Tanzania:understanding ui in_android
Denis Minja
 
Mobile Application Development -Lecture 09 & 10.pdf
AbdullahMunir32
 
Android App Development 03 : Widget &amp; UI
Anuchit Chalothorn
 
07.3. Android Alert message, List, Dropdown, and Auto Complete
Oum Saokosal
 
Android App Development - 11 Lists, grids, adapters, dialogs and toasts
Diego Grancini
 
"Android" mobilių programėlių kūrimo įvadas #2
Tadas Jurelevičius
 
Android app development
Vara Prasad Kanakam
 
Android App Development (Basics)
Alberto Rubalcaba Stockman
 
Ad

More from info_zybotech (8)

DOCX
Accessing data with android cursors
info_zybotech
 
DOCX
Notepad tutorial
info_zybotech
 
DOCX
Java and xml
info_zybotech
 
DOCX
How to create ui using droid draw
info_zybotech
 
DOCX
Applications
info_zybotech
 
DOCX
Android database tutorial
info_zybotech
 
DOCX
Android accelerometer sensor tutorial
info_zybotech
 
DOCX
Accessing data with android cursors
info_zybotech
 
Accessing data with android cursors
info_zybotech
 
Notepad tutorial
info_zybotech
 
Java and xml
info_zybotech
 
How to create ui using droid draw
info_zybotech
 
Applications
info_zybotech
 
Android database tutorial
info_zybotech
 
Android accelerometer sensor tutorial
info_zybotech
 
Accessing data with android cursors
info_zybotech
 

Recently uploaded (20)

PDF
The-Beginnings-of-Indian-Civilisation.pdf/6th class new ncert social/by k san...
Sandeep Swamy
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PDF
Zoology (Animal Physiology) practical Manual
raviralanaresh2
 
PPTX
How to Manage Promotions in Odoo 18 Sales
Celine George
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
SCHOOL-BASED SEXUAL HARASSMENT PREVENTION AND RESPONSE WORKSHOP
komlalokoe
 
PPSX
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
PPTX
HEAD INJURY IN CHILDREN: NURSING MANAGEMENGT.pptx
PRADEEP ABOTHU
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PPTX
How to Configure Prepayments in Odoo 18 Sales
Celine George
 
PPTX
How to Create Rental Orders in Odoo 18 Rental
Celine George
 
PDF
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PDF
1, 2, 3… E MAIS UM CICLO CHEGA AO FIM!.pdf
Colégio Santa Teresinha
 
PPSX
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
PPTX
Views on Education of Indian Thinkers J.Krishnamurthy..pptx
ShrutiMahanta1
 
PPTX
How to Manage Access Rights & User Types in Odoo 18
Celine George
 
PPTX
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
PDF
BÀI TẬP BỔ TRỢ THEO LESSON TIẾNG ANH - I-LEARN SMART WORLD 7 - CẢ NĂM - CÓ ĐÁ...
Nguyen Thanh Tu Collection
 
The-Beginnings-of-Indian-Civilisation.pdf/6th class new ncert social/by k san...
Sandeep Swamy
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
Zoology (Animal Physiology) practical Manual
raviralanaresh2
 
How to Manage Promotions in Odoo 18 Sales
Celine George
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
SCHOOL-BASED SEXUAL HARASSMENT PREVENTION AND RESPONSE WORKSHOP
komlalokoe
 
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
HEAD INJURY IN CHILDREN: NURSING MANAGEMENGT.pptx
PRADEEP ABOTHU
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
How to Configure Prepayments in Odoo 18 Sales
Celine George
 
How to Create Rental Orders in Odoo 18 Rental
Celine George
 
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
1, 2, 3… E MAIS UM CICLO CHEGA AO FIM!.pdf
Colégio Santa Teresinha
 
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
Views on Education of Indian Thinkers J.Krishnamurthy..pptx
ShrutiMahanta1
 
How to Manage Access Rights & User Types in Odoo 18
Celine George
 
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
BÀI TẬP BỔ TRỢ THEO LESSON TIẾNG ANH - I-LEARN SMART WORLD 7 - CẢ NĂM - CÓ ĐÁ...
Nguyen Thanh Tu Collection
 

Android basics – dialogs and floating activities

  • 1. Android Application Development Training Tutorial For more info visit http://www.zybotech.in A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 2. Android Basics – Dialogs and Floating Activities As we know android provide Activity class for developing application screens. But many a time application needs to show Dialog boxes or floating screen to do simple tasks likes taking input from user or ask for confirmation etc. In android Dialogs can be created in following 2 ways: 1. Creating a dialog with the help of android Dialog class or its subclass like AlertDialog. 2. Using dialog theme for the activity. Using android Dialog class: Let see how we can create a dialog with the help of Dialog class. To define a dialog the dialog class has to extend the android Dialog class. class MyDialog extends Dialog { /** * @param context */ public MyDialog(Context context) { super(context); } } Define a layout for our dialog. Here is the xml file for of the layout that asks for user’s name. <?xml version=”1.0″ encoding=”utf-8″?> <LinearLayout android:id="@+id/widget28" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android" > <TextView android:id="@+id/nameMessage" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Enter Name:" > </TextView> <EditText android:id="@+id/nameEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="18sp" > </EditText> <LinearLayout A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 3. android:id="@+id/buttonLayout" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" > <Button android:id="@+id/okButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="OK" > </Button> <Button android:id="@+id/cancelButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cancel" > </Button> </LinearLayout> </LinearLayout> Use the above layout for our dialog class MyDialog extends Dialog { .... /** * @see android.app.Dialog#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("TestApp", "Dialog created"); setContentView(R.layout.mydialog); } } Now the dialog can be shown by calling the show method like this … MyDialog dialog = new MyDialog(context); dialog.show(); … A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 4. Event handling for the Dialog controls are same as in case of the activity. Modify the dialog code to handle the onclick event on the ok and cancel button. class MyDialog extends Dialog implements OnClickListener { private Button okButton; private Button cancelButton; private EditText nameEditText; protected void onCreate(Bundle savedInstanceState) { okButton = (Button) findViewById(R.id.okButton); cancelButton = (Button) findViewById(R.id.cancelButton); nameEditText = (EditText) findViewById(R.id.nameEditText); okButton.setOnClickListener(this); cancelButton.setOnClickListener(this); } public void onClick(View view) { switch (view.getId()) { case R.id.okButton: dismiss(); break; case R.id.cancelButton: cancel(); break; } } } To close the dialog the dismiss() method can be called. The dialog can call the dismiss method itself or some other code can also close the dialog by calling dismiss(). A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 5. The dialog also supports cancel. Canceling means the dialog action is canceled and does not need to perform any operation. Dialog can be canceled by calling cancel() method. Canceling the dialog also dismisses the dialog. When user clicks the phones BACK button the dialog gets canceled. If you do not want to cancel the dialog on BACK button you can set cancelable to false as setCancelable(false); Note that the cancel() method call till be able to cancel the dialog (which is the desirable functionality in most cases). The dialog’s cancel and dismiss events can be listened with the help of OnCancelListener and OnDismissListener. Returning information from dialog: Now our dialog can take the name from the user. We need to pass that name to the calling activity. Dialog class does not provide any direct method for returning values. But our own Listener can be created as follows: public interface MyDialogListener { public void onOkClick(String name); // User name is provided here. public void onCancelClick(); } The dialog’s constructor has to be modified to take the object of the listener: public MyDialog(Context context, MyDialogListener listener) { super(context); this.listener = listener; } Now the calling activity needs to provide the object of the class that implements the MyDialogListener which will gets called on ok or cancel button clicks. Now we need update the onclick method to return the user name. public void onClick(View view) { switch (view.getId()) { case R.id.okButton: listener.onOkClick(nameEditText.getText().toString()); // returning the user's name. dismiss(); break; case R.id.cancelButton: cancel(); break; } } Using AlertDialog: AlertDialog is the subclass of the Dialog. It by default provide 3 buttons and text message. The buttons can be made visible as required. Following code creates an AlertDialog that ask user a question and provide Yes, No option. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 6. AlertDialog dialog = new AlertDialog.Builder(context).create(); dialog.setMessage("Do you play cricket?"); dialog.setButton("Yes", myOnClickListener); dialog.setButton2("No", myOnClickListener); dialog.show(); The onClick method code for the button listener myOnClickListener will be like this: public void onClick(DialogInterface dialog, int i) { switch (i) { case AlertDialog.BUTTON1: /* Button1 is clicked. Do something */ break; case AlertDialog.BUTTON2: /* Button2 is clicked. Do something */ break; } } AlertDialog.Builder: AlertDialog has a nested class called ‘Builder’. Builder class provides facility to add multichoice or single choice lists. The class also provides methods to set the appropriate Adaptors for the lists, set event handlers for the list events etc. The Builder button calls the Button1, Button2, Button3 as PositiveButton, NeutralButton, NegativeButton. Here is an example of dialog box with Multichoice list new AlertDialog.Builder(context) .setIcon(R.drawable.icon) .setTitle(R.string.alert_dialog_multi_choice) .setMultiChoiceItems(R.array.select_dialog_items, new boolean[]{false, true, false, true, false}, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) { /* Something on click of the check box */ } }) .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked Yes so do some stuff */ } }) .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked No so do some stuff */ A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 7. } }) .create(); Activity Managed Dialog: Android also provide facility to create dialogs. Activity created dialog can be managed by Activity methods like showDialog(), onCreateDialog(), onPrepareDialog(), dismissDialog(), removeDialog(). The onCreateDialog create the dialog that needs to be shown, for example /** * @see android.app.Activity#onCreateDialog(int) */ @Override protected Dialog onCreateDialog(int id) { return new AlertDialog.Builder(this).setMessage("How are you?").setPositiveButton("Fine", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { /* Do something here */ } }).setNegativeButton("Not so good", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { /* Do something here */ } }).create(); } You can create multiple dialog boxes and differentiate them with the id parameter. The dialog can be shown with the help of showDialog(id) method. The onCreateDialog method gets called for the first time when showDialog method is called. For subsequent calls to the showDialog() the dialog is not created but shown directly. If you need to update the dialog before it is getting shown then you can do that in onPrepareDialog() method. The methods get called just before the dialog is shown to the user. To close the dialog you can call dismissDialog() method. Generally you will dismiss the dialogs in the click handles of the dialog buttons. The removeDialog() method will remove the dialog from the activity management and if showDialog is again called for that dialog, the dialog needs to be created. Using android Dialog theme for activity: Another simple way to show the dialog is to make the Activity to work as a Dialog (floating activity). This can be done by applying dialog Theme while defining the activity entry in the AndroidManifest.xml A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 8. <activity android:name=”.DialogActivity” android:label=”@string/activity_dialog” android:theme=”@android:style/Theme.Dialog”> … </activity> The activity will be shown as a dialog as the activity is using ‘Theme.Dialog’ as theme. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi