Android tutorials | android creating menus-dialogs by apk855


More Info
									Android - Menus & Dialogs
                                          - Android Apps Development Team

    Copyright © 2012, . All rights
    1. Menus Basics

•   What is a Menu?
•   It is a mechanism to expose the application’s functionality without
    consuming the view space

•   Types of Menus
     • Options Menu: The primary menu for an Activity, which appears when the
       user presses the device MENU key (Menu Key on hardware device), it contains icon
       menu and expanded menu
     • Context Menu: A floating list of menu items that appears when the user
       performs a long-press on a View
     • Sub-menu: A floating list of menu items that the user opens by pressing a
       menu item in the Options Menu or a context menu

                               Copyright © 2012, . All rights
    Menus Basics – Options Menu

•   Options Menu
    • Basic Application functions can be added under this menu
    • The user can open the Options Menu with the device MENU key
    • the first visible portion of the Options Menu is called a Menu
    • Menu will hold the first six menu items.
    • If added more than six items to the Options Menu, Android places
      the sixth item and those after it into the Expanded Menu, which the
      user can open with the "More" menu item

                          Copyright © 2012, . All rights
    Menus Basics – Options Menu

•    Defining and Inflating Menus
     • Define menu and its items in the XML menu resource file
     • Inflate the menu resource from the application’s source code

•    Create XML file in res/menu/ directory
      <?xml version="1.0" encoding="utf-8"?>
      <menu xmlns:android="">
        <item android:id="@+id/new_game"
            android:title="@string/new_game" />
        <item android:id="@+id/quit"
            android:title="@string/quit" />

                             Copyright © 2012, . All rights
    Menus Basics – Options Menu

•    Inflating the menu resource from the Activity,

     public boolean onCreateOptionsMenu(Menu menu) {
                MenuInflater inflater = getMenuInflater();
                inflater.inflate(, menu);
                return true;

                            Copyright © 2012, . All rights
    Menus Basics – Context menu

•    A context menu is conceptually similar to the menu displayed when the user
     performs a "right-click" on a PC
•    On Android, a context menu is displayed when the user performs a "long press"
     (press and hold) on an item
•    Application a can create a context menu for any View
•    In order for a View to provide a context menu, you must "register" the view for a
     context menu
•    Call registerForContextMenu() and pass it the View we want to give a context
     menu. When this View receives a long-press, it displays a context menu
•    To define the context menu's appearance and behavior, override your Activity's
     context      menu      callback    methods,     onCreateContextMenu()        and

                              Copyright © 2012, . All rights
    Menus Basics – Context Menu

•   For example, here's an onCreateContextMenu() that uses the
    context_menu.xml menu resource:
    public void onCreateContextMenu(ContextMenu menu, View v,
                        ContextMenuInfo menuInfo) {
                 super.onCreateContextMenu(menu, v, menuInfo);
                 MenuInflater inflater = getMenuInflater();
                 inflater.inflate(, menu);

•   Handling the selected item using onContextItemSelected()
     public boolean onContextItemSelected(MenuItem item) {
                 AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
                 switch (item.getItemId()) {
                   return true;
                   return true;
                                return super.onContextItemSelected(item);
                                      Copyright © 2012, . All rights
    Menus Basics - Submenus

•   A submenu is a menu that the user can open by selecting an item in
    another menu.
•   You can add a submenu to any menu, except another submenu
•   When creating your menu resource, you can create a submenu by adding
    a <menu> element as the child of an <item>.
•   Android does not support nested submenus

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="">
      <item android:id="@+id/file"
          android:title="@string/file" >
         <!-- "file" submenu -->
            <item android:id="@+id/new"
                android:title="@string/new" />
            <item android:id="@+id/open"
                android:title="@string/open" />

                                      Copyright © 2012, . All rights
    Menus – Other Menu Features

•   Menu groups
    •   A menu group is a collection of menu items that has similar nature
    •   Show or hide all items
    •   Enable or disable all items
    •   Specify whether items are checkable
    •   You can create a group by nesting <item> elements inside a <group> element
        in your menu resource
        <?xml version="1.0" encoding="utf-8"?>
        <menu xmlns:android="">
          <item android:id="@+id/item1"
              android:title="@string/item1" />
          <!-- menu group -->
          <group android:id="@+id/group1">
             <item android:id="@+id/groupItem1"
                 android:title="@string/groupItem1" />
             <item android:id="@+id/groupItem2"
                 android:title="@string/groupItem2" />

                                      Copyright © 2012, . All rights
    Menus – Other Menu Features

•   Checkable Menu Items
    • Used as an option to turn on or off
    • Options are check buttons, radio buttons
    • Uses android:checkableBehaviorattribute in the <group> elements,
    • This attribute accepts, Single (Radio buttons) or All (Check boxes)
    • Example:
     <?xml version="1.0" encoding="utf-8"?>
     <menu xmlns:android="">
       <group android:checkableBehavior="single">
         <item android:id="@+id/red"
             android:title="@string/red" />
         <item android:id="@+id/blue"
             android:title="@string/blue" />

                                  Copyright © 2012, . All rights
    Menus - – Other Menu Features

•   Shortcut Keys
    • To have a quick-access, shortcut keys are used using letters and/or numbers
      to menu items
    • Attributes used along with the <item> element are android:alphabeticShortcut
      andandroid:numericShortcut attributes
    • Shortcut keys for menu items only work on devices with a hardware keyboard.
    • Shortcuts cannot be added to items in a Context Menu.

                             Copyright © 2012, . All rights

  Copyright © 2012, . All rights
    2. Dialog Boxes

•   What is a Dialog Box ?

    • Dialog boxes in Android are floating Activities.

    • A dialog is a small window that appears in front of the current Activity.

    • The underlying Activity loses focus and the dialog accepts all user

    • Dialogs are normally used to make selections, and confirm actions,
      and to display warning or error messages.

    • is base class for dialogs.

                             Copyright © 2012, . All rights
    Dialog Boxes

•   Types of Dialog Boxes
•   The Android API supports the following types of Dialog objects:
•   AlertDialog A dialog that can manage zero, one, two, or three buttons,
    and/or a list of selectable items that can include checkboxes or radio
    buttons etc.

                           Copyright © 2012, . All rights
    Dialog Boxes

•   ProgressDialog: A dialog that displays a progress wheel or progress
    bar.It's an extension of the AlertDialog.
     • DatePickerDialog: A dialog that allows the user to select a date.
     • TimePickerDialog:A dialog that allows the user to select a time.

                          Copyright © 2012, . All rights
     Dialog Boxes

•     Programming Example using AlertDialog
          Eclipse Example code

     // Create a builder (AlertDialog.Builder – Nested class of AlertDialog)
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Alert Window");

    // add buttons and listener
    DialogListener dialogListener = new DialogListener() ;

    builder.setPositiveButton("Ok", dialogListener);
    builder.setNegativeButton("Cancel", dialogListener);
    builder.setMessage("Alert Dialog Box");

    // Create the dialog
    AlertDialog ad = builder.create();

    // show created dialog;

                                         Copyright © 2012, . All rights
    Dialog Boxes

class DialogListener implements android.content.DialogInterface.OnClickListener {

       public void onClick(DialogInterface v, int buttonId) {

         if (buttonId == DialogInterface.BUTTON1) {
       System.out.println("positive button clicked") ;
         }else {
                    System.out.println("negative button clicked") ;
               ad.dismiss() ;


•   Disadvantages of creating dialogs as above
     •  Repetition of code
     •  Window leakages

                                   Copyright © 2012, . All rights
    Dialog Boxes

•   Managing Dialogs (Saving state of dialogs)

    Android system automatically manages and saves the state of each dialog.
    For that purpose Android provides following methods in Activity class

    onCreateDialog() , onPrepareDialog() , showDialog()
    dismissDialog() , removeDialog()

•   onCreateDialog()

    Android calls this method when we request a dialog for first time. It instantiates
       the Dialog

    onCreateDialog(int) is only called the very first time a dialog is opened

                                Copyright © 2012, . All rights
    Dialog Boxes

•   onPrepareDialog()
    Android calls this optional method before the dialog is displayed.
    Define this method if you want to change any properties of the dialog each time it
        is opened.
    This method is called every time a dialog is opened
    If you don't define onPrepareDialog(), then the dialog will remain the same as it
        was the previous time it was opened.

•   showDialog()

    Called to display a dialog, call showDialog()

• dismissDialog()
    Used to dismiss a previously shown dialog

                               Copyright © 2012, . All rights
    Dialog Boxes

•   removeDialog()
    Removes any internal references to a dialog managed by this Activity
        This can be called if we know that we will never show a dialog again

         • Show sample code in eclipse

                               Copyright © 2012, . All rights
     Dialog Boxes

•    Creating custom dialogs
      We can create our own layouts for the dialog windows by using Dialog class or
    AlertDialog class.

         For Dialog class pass the layout resource ID to setContentView()

                  Dialog dialog = new Dialog(this);

         For AlertDialog class

             Create a view by inflating the layout resource using LayoutInflater class

                     LayoutInflater li = LayoutInflater.from(this);
                     View view = li.inflate(R.layout.addassay_dialog, null);

             Pass the view to setView() method.

                  AlertDialog.Builder builder = new AlertDialog.Builder(this);
                  builder.setView(view1); alertDialog = builder.create();
                                    Copyright © 2012, . All rights
    Dialog Boxes

•   Title of a dialog
    A dialog made with the base Dialog class must have a title. If you don't
    call setTitle(), then the space used for the title remains empty, but still visible.

        If you don't want a title at all, then you should create your custom dialog
          using the AlertDialog class.

    •    Handling device Back button events

                                 Copyright © 2012, . All rights
Dialog Boxes

• Sample example on Eclipse

                     Copyright © 2012, . All rights

 Copyright © 2012, . All rights

To top