miércoles, 17 de abril de 2013

Action Bar (Crear Botones de Accion)


Añadir botones de acción

Un item de acción es simplemente un item de menú del menú de opciones que debería aparecer en la barra de acción. Un item de acción puede incluir un icono y/o texto. Si un item de menú no aparece como un item de acción , el sistema lo coloca en un overflow menu, que el usuario puede abrir con el icono del menú en la parte derecha de la barra de acción.

Figura 2. Pantallazo de una barra de acción con dos items de acción y el overflow menu.
Cuando la actividad se inicia, el sistema rellena la barra de acción y el overflow menu llamando al método onCreateOptionsMenu(). Tal y como se detalla en la sección Crear menús, es en este método callback donde se define el menú de opciones para la actividad.
Se puede hacer que item del menú aparezca como un item de acción—si existe lugar para él—desde el recurso de menú mediante la declaración del android:showAsAction="ifRoom" para el elemento <item>. De esta manera, el item del menú aparece como acceso directo en la barra de acción sólo si existe lugar para ello. Si no hay suficiente lugar, el item se coloca en el overflow menu (mostrado por el icon del menú en la parte derecha de la barra de acción).
También se puede declarar un item del menú para que aparezca como un item de acción en el código de la aplicación, llamando al método setShowAsAction() en el MenuItem y pasándole SHOW_AS_ACTION_IF_ROOM.
Si el item del menú tiene un título y un icono, el item de acción, por defecto sólo muestra el icono. Si se quiere incluir el texto con el item de acción, hay que añadir el flag "with text": en el XML, añadir withText al atributo android:showAsAction o, utilizar en el código de la aplicación el flag SHOW_AS_ACTION_WITH_TEXT cuando se llama al método setShowAsAction(). La figura 2 muestra una barra de acción que tiene dos items de acción con su texto y el icono para el overflow menu.


A continuación tenemos un ejemplo de cómo se puede declarar un item de menú como un item de acción en un archivo recurso de menú:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_add"
          android:icon="@drawable/ic_menu_save"
          android:title="@string/menu_save"
          android:showAsAction="ifRoom|withText" />
</menu>
En este caso, los dos flags ifRoom y withText están seteados, por lo que cuando este item aparece como un item de acción, incluye el texto del título junto con el icono.
Un item de menú colocado en la barra de acción dispara los mismos métodos callback que otros items del menú de opciones. Cuando el usuario selecciona un item de acción, la actividad recibe una llamada al método onOptionsItemSelected(), pasándole el item ID.
Nota: Si se añade un item del menú desde un fragmento, se llama al método onOptionsItemSelected()correspondiente para ese fragmento. Si la actividad lo maneja primero, el sistema llama al método onOptionsItemSelected() de la actividad antes de llamar al fragmento.

También se puede declarar un item para que aparezca siempre como un item de acción, pero se debe evitar, ya que puede crear una IU recargada debido a la presencia de demasiados items de acción y pueden llegar a chocar con otros elementos de la barra de acción.
Para más información sobre los menús, ver el documento sobre Crear menús.


Sintaxis:

Lo mas importante viene marcado en rojo

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@[+][package:]id/resource_name"
          android:title="string"
          android:titleCondensed="string"
          android:icon="@[package:]drawable/drawable_resource_name"
          android:onClick="method name"
          android:showAsAction=["ifRoom" | "never" | "withText" | "always"]
          android:actionLayout="@[package:]layout/layout_resource_name"
          android:actionViewClass="class name"
          android:alphabeticShortcut="string"
          android:numericShortcut="string"
          android:checkable=["true" | "false"]
          android:visible=["true" | "false"]
          android:enabled=["true" | "false"]
          android:menuCategory=["container" | "system" | "secondary" | "alternative"]
          android:orderInCategory="integer" />
    <group android:id="@[+][package:]id/resource name"
           android:checkableBehavior=["none" | "all" | "single"]
           android:visible=["true" | "false"]
           android:enabled=["true" | "false"]
           android:menuCategory=["container" | "system" | "secondary" | "alternative"]
           android:orderInCategory="integer" >
        <item />
    </group>
    <item >
        <menu>
          <item />
        </menu>
    </item>
</menu>
elements:
Required. This must be the root node. Contains <item> and/or <group> elements.
attributes:
xmlns:android
XML namespaceRequired. Defines the XML namespace, which must be"http://schemas.android.com/apk/res/android".
<item>
A menu item. May contain a <menu> element (for a Sub Menu). Must be a child of a <menu> or <group>element.
attributes:
android:id
Resource ID. A unique resource ID. To create a new resource ID for this item, use the form:"@+id/name". The plus symbol indicates that this should be created as a new ID.
android:title
String resource. The menu title as a string resource or raw string.
android:titleCondensed
String resource. A condensed title as a string resource or a raw string. This title is used for situations in which the normal title is too long.
android:icon
Drawable resource. An image to be used as the menu item icon.
android:onClick
Method name. The method to call when this menu item is clicked. The method must be declared in the activity as public and accept a MenuItem as its only parameter, which indicates the item clicked. This method takes precedence over the standard callback to onOptionsItemSelected(). See the example at the bottom.
Warning: If you obfuscate your code using ProGuard (or a similar tool), be sure to exclude the method you specify in this attribute from renaming, because it can break the functionality.
Introduced in API Level 11.
android:showAsAction
Keyword. When and how this item should appear as an action item in the Action Bar. A menu item can appear as an action item only when the activity includes an ActionBar (introduced in API Level 11). Valid values:
ValueDescription
ifRoomOnly place this item in the Action Bar if there is room for it.
withTextAlso include the title text (defined by android:title) with the action item. You can include this value along with one of the others as a flag set, by separating them with a pipe |.
neverNever place this item in the Action Bar.
alwaysAlways place this item in the Action Bar. Avoid using this unless it's critical that the item always appear in the action bar. Setting multiple items to always appear as action items can result in them overlapping with other UI in the action bar.
See Using the Action Bar for more information.
Introduced in API Level 11.
android:actionViewLayout
Layout resource. A layout to use as the action view.
See Using the Action Bar for more information.
Introduced in API Level 11.
android:actionViewClassName
Class name. A fully-qualified class name for the View to use as the action view.
See Using the Action Bar for more information.
Warning: If you obfuscate your code using ProGuard (or a similar tool), be sure to exclude the class you specify in this attribute from renaming, because it can break the functionality.
Introduced in API Level 11.
android:alphabeticShortcut
Char. A character for the alphabetic shortcut key.
android:numericShortcut
Integer. A number for the numeric shortcut key.
android:checkable
Boolean. "true" if the item is checkable.
android:checked
Boolean. "true" if the item is checked by default.
android:visible
Boolean. "true" if the item is visible by default.
android:enabled
Boolean. "true" if the item is enabled by default.
android:menuCategory
Keyword. Value corresponding to Menu CATEGORY_* constants, which define the item's priority. Valid values:
ValueDescription
containerFor items that are part of a container.
systemFor items that are provided by the system.
secondaryFor items that are user-supplied secondary (infrequently used) options.
alternativeFor items that are alternative actions on the data that is currently displayed.
android:orderInCategory
Integer. The order of "importance" of the item, within a group.
<group>
A menu group (to create a collection of items that share traits, such as whether they are visible, enabled, or checkable). Contains one or more <item> elements. Must be a child of a <menu> element.
attributes:
android:id
Resource ID. A unique resource ID. To create a new resource ID for this item, use the form:"@+id/name". The plus symbol indicates that this should be created as a new ID.
android:checkableBehavior
Keyword. The type of checkable behavior for the group. Valid values:
ValueDescription
noneNot checkable
allAll items can be checked (use checkboxes)
singleOnly one item can be checked (use radio buttons)
android:visible
Boolean. "true" if the group is visible.
android:enabled
Boolean. "true" if the group is enabled.
android:menuCategory
Keyword. Value corresponding to Menu CATEGORY_* constants, which define the group's priority. Valid values:
ValueDescription
containerFor groups that are part of a container.
systemFor groups that are provided by the system.
secondaryFor groups that are user-supplied secondary (infrequently used) options.
alternativeFor groups that are alternative actions on the data that is currently displayed.
android:orderInCategory
Integer. The default order of the items within the category.
example:
XML file saved at res/menu/example_menu.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/item1"
          android:title="@string/item1"
          android:icon="@drawable/group_item1_icon"
          android:showAsAction="ifRoom|withText"/>
    <group android:id="@+id/group">
        <item android:id="@+id/group_item1"
              android:onClick="onGroupItemClick"
              android:title="@string/group_item1"
              android:icon="@drawable/group_item1_icon" />
        <item android:id="@+id/group_item2"
              android:onClick="onGroupItemClick"
              android:title="@string/group_item2"
              android:icon="@drawable/group_item2_icon" />
    </group>
    <item android:id="@+id/submenu"
          android:title="@string/submenu_title"
          android:showAsAction="ifRoom|withText" >
        <menu>
            <item android:id="@+id/submenu_item1"
                  android:title="@string/submenu_item1" />
        </menu>
    </item>
</menu>
The following application code inflates the menu from the onCreateOptionsMenu(Menu) callback and also declares the on-click callback for two of the items:
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.example_menu, menu);
    return true;
}

public void onGroupItemClick(MenuItem item) {
    // One of the group items (using the onClick attribute) was clicked
    // The item parameter passed here indicates which item it is
    // All other menu item clicks are handled by onOptionsItemSelected()
}
Note: The android:showAsAction attribute is available only on Android 3.0 (API Level 11) and greater.

1 comentario:

  1. mil gracias por conpartir esta informacion es de muchisisisiisma utilidad esta muy bien especificada =3 gracias :D

    ResponderEliminar