Android basics – dialogs and floating activities


Published on

Android Training

Published in: Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Android basics – dialogs and floating activities

  1. 1. Android Application Development Training Tutorial For more info visit A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  2. 2. Android Basics – Dialogs and Floating ActivitiesAs we know android provide Activity class for developing application screens. But many a time applicationneeds to show Dialog boxes or floating screen to do simple tasks likes taking input from user or ask forconfirmation 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 toextend 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″?><LinearLayoutandroid:id="@+id/widget28"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical"xmlns:android=""><TextViewandroid:id="@+id/nameMessage"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Enter Name:"></TextView><EditTextandroid: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. 3. android:id="@+id/buttonLayout"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_gravity="center_horizontal"><Buttonandroid:id="@+id/okButton"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="OK"></Button><Buttonandroid: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 dialogclass MyDialog extends Dialog {..../*** @see*/@Overrideprotected 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);;… A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  4. 4. Event handling for the Dialog controls are same as in case of the activity. Modify the dialog code to handle theonclick 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(;cancelButton = (Button) findViewById(;nameEditText = (EditText) findViewById(;okButton.setOnClickListener(this);cancelButton.setOnClickListener(this);}public void onClick(View view) {switch (view.getId()) {case;break;case;break;}}}To close the dialog the dismiss() method can be called. The dialog can call the dismiss method itself or someother code can also close the dialog by calling dismiss(). A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  5. 5. The dialog also supports cancel. Canceling means the dialog action is canceled and does not need to performany operation. Dialog can be canceled by calling cancel() method. Canceling the dialog also dismisses thedialog.When user clicks the phones BACK button the dialog gets canceled. If you do not want to cancel the dialog onBACK button you can set cancelable to false assetCancelable(false);Note that the cancel() method call till be able to cancel the dialog (which is the desirable functionality in mostcases). The dialog’s cancel and dismiss events can be listened with the help of OnCancelListener andOnDismissListener.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 classdoes 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 whichwill 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; // returning the users name.dismiss();break;case;break;}}Using AlertDialog:AlertDialog is the subclass of the Dialog. It by default provide 3 buttons and text message. The buttons can bemade visible as required. Following code creates an AlertDialog that ask user a question and provide Yes, Nooption. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  6. 6. AlertDialog dialog = new AlertDialog.Builder(context).create();dialog.setMessage("Do you play cricket?");dialog.setButton("Yes", myOnClickListener);dialog.setButton2("No", myOnClickListener);;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 singlechoice lists. The class also provides methods to set the appropriate Adaptors for the lists, set event handlers forthe list events etc. The Builder button calls the Button1, Button2, Button3 as PositiveButton, NeutralButton,NegativeButton.Here is an example of dialog box with Multichoice listnew 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. 7. }}).create();Activity Managed Dialog:Android also provide facility to create dialogs. Activity created dialog can be managed by Activity methodslike showDialog(), onCreateDialog(), onPrepareDialog(), dismissDialog(), removeDialog().The onCreateDialog create the dialog that needs to be shown, for example/*** @see*/@Overrideprotected 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 shownwith the help of showDialog(id) method. The onCreateDialog method gets called for the first time whenshowDialog method is called. For subsequent calls to the showDialog() the dialog is not created but showndirectly.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 clickhandles of the dialog buttons.The removeDialog() method will remove the dialog from the activity management and if showDialog is againcalled 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 canbe done by applying dialog Theme while defining the activity entry in the AndroidManifest.xml A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  8. 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