Uncategorized

Menus

YOU ARE READING: Menus AT Vccidata_En

Menus are a common user interface component in many types of applications. To provide a familiar and consistent user experience, consider using the menu APIs to represent user actions and other options in your activities.

Android devices no longer exist as of Android 3.0 (API level 11). required to provide a dedicated menu button. With this change, Android apps should migrate away from a dependency on the traditional 6-item menu box and instead provide an app bar to represent common user actions.

Reading: How to create an options menu in the app bar

Although the design and user experience for some menu items have changed, the semantics for defining a set of actions and options are still based on the menu APIs. This guide shows how to create the three basic types of menus or action presentations on all versions of Android:

Options Menu and App Bar The options menu is the primary collection of menu items for an activity. This is where you should place actions that affect the app globally, e.g. B. “Search”, “Compose email” and “Settings”.

See the section on creating an options menu.

Context menu and contextual action mode A context menu is a floating menu that appears when the user long-clicks on an item. It provides actions that affect the selected content or context frame.

The contextual action mode displays action items that affect the selected content in a bar at the top of the screen and allows the user to select multiple items.

See the section on creating context menus.

p> Popup Menu A popup menu displays a list of items in a vertical list that is anchored to the view that invoked the menu. It’s good for providing an overflow of actions related to specific content, or for providing options for a second part of a command. Actions in a pop-up menu should not affect the corresponding content directly – that’s what context actions are for. Rather, the pop-up menu is for advanced actions related to content areas in your activity.

See the section on creating a pop-up menu.

Defining a menu in XML

Android provides a standard XML format for defining menu items for all menu types. Instead of creating a menu in your activity’s code, you should define a menu and all of its elements in an XML menu resource. You can then inflate (load as a menu object) the menu resource in your activity or fragment.

Using a menu resource is recommended for several reasons:

  • It’s easier to use the Visualize menu structure in XML.
  • It separates the content for the menu from your application’s behavior code.
  • It allows you to create alternative menu configurations for different platform versions, screen sizes and other configurations by You use the app resource framework.

To define the menu, create an XML file in the res/menu/ directory of your project and create the menu with the following elements :

Defines a menu, which is a container for menu items. A

element must be the root node for the file and can contain one or more and elements. Creates a MenuItem that represents a single item on a menu. This element can contain a nested

element to create a submenu. An optional invisible container for elements. It allows you to categorize menu items so that they have common properties like active status and visibility. See the section on creating menu groups for more information.

Here is an example menu called game_menu.xml:

The element supports multiple attributes used to define the appearance and behavior of an element. The items in the above menu contain the following attributes:

android:id A resource ID unique to the item, allowing the application to recognize the item when the user selects it. android:icon A reference to a drawable that can be used as the element’s icon. android:title A reference to a string to use as the item’s title. android:showAsAction Specifies when and how this item should be shown as an action item in the app bar.

These are the most important attributes to use, but there are many more available. See the menu resources document for all supported attributes.

You can add a submenu to an item in any menu by adding a

element as a child of an . Submenus are useful when your application has many functions that can be organized into topics, such as B. Items in the menu bar of a PC application (File, Edit, View, etc.).For example:

To If you use the menu in your activity, you need to inflate the menu resource (convert the XML resource into a programmable object) using MenuInflater.inflate(). In the following sections you will see how to inflate a menu for each menu type.

Create an options menu

In the options menu you should include actions and other options relevant to the current activity context, e.g . B. Search, Compose Email, and Settings.

Where the items in your options menu appear on the screen depends on the version you developed your application for:

  • If you have developed your application for Android 2.3.x (API level 10) or lower, the contents of your options menu will appear at at the top of the screen, when the user presses the menu button as shown in Figure 1. When opened, the first visible part is the icon menu, which contains up to six menu items. If your menu contains more than six items, Android places the sixth item and the rest in the overflow menu, which the user can open by selecting More.
  • If you developed your application for Android 3.0 (API level 11) and above items are available from the options menu in the app bar. By default, the system places all items in the action overflow, which the user can view using the action overflow icon on the right side of the app bar (or by pressing the device’s menu button, if available). To provide quick access to important actions, you can show some items in the app bar by adding android:showAsAction=”ifRoom” to the appropriate elements (see Figure 2).

    For more information on action items and other app bar behaviors, see the Adding the App Bar training class.

Figure 2. The Google Sheets app showing multiple buttons, including the action overflow button.

You can declare options menu items from either your Activity subclass or a Fragment subclass. If both your activity and fragment(s) declare options menu items, they will be combined in the UI. The elements of the activity appear first, followed by those of each fragment in the order that each fragment is added to the activity. If necessary, you can reorder the menu items using the android:orderInCategory attribute in each that you need to move.

See also  How to Build an Affiliate Website with WordPress

To specify the options menu for an activity, override onCreateOptionsMenu() (offer fragments its own onCreateOptionsMenu() callback). With this method you can inflate your menu resource (defined in XML) into the menu provided in the callback. For example:

You can also add menu items with add() and retrieve items with findItem() to revise their properties with MenuItem APIs.

If you develop your application for have Android 2.3.x and below, the system calls onCreateOptionsMenu() to create the options menu when the user opens the menu for the first time. If you developed for Android 3.0 and above, when the activity starts, the system calls onCreateOptionsMenu() to display items in the app bar.

Handling of click events

When the When the user selects an item from the options menu (including action items in the app bar), the system calls your activity’s onOptionsItemSelected() method. This method passes the selected MenuItem. You can identify the item by calling getItemId(), which returns the unique ID for the menu item (defined by the android:id attribute in the menu resource, or with an integer passed to the add() method). You can match this ID to known menu items to take the appropriate action. For example:

If you successfully edit a menu item, return true. If you don’t handle the menu item, you should call the superclass implementation of onOptionsItemSelected() (the default implementation returns false).

If your activity contains fragments, the system calls onOptionsItemSelected() first on the activity, then on each fragment (in the order each fragment was added) until one returns true or all fragments have been invoked.

Tip: Android 3.0 adds the ability you define the on-click behavior for a menu item in XML using the android:onClick attribute. The value for the attribute must be the name of a method defined by the activity using the menu. The method must be public and accept a single MenuItem parameter – when the system calls this method, it passes the selected menu item.For more information and an example, see the Menu Resources document.

Tip: If your application contains multiple activities and some of them offer the same menu of options, you should create an activity that implements nothing but the onCreateOptionsMenu() and onOptionsItemSelected() methods. Then extend this class for each activity that should use the same options menu. This allows you to maintain a set of code for handling menu actions, and each child class inherits the menu behavior. If you want to add menu items to one of the child activities, override onCreateOptionsMenu() in that activity. Call super.onCreateOptionsMenu(menu) to create the original menu items, then use menu.add() to add new menu items. You can also override the behavior of the superclass for individual menu items.

Changing menu items at runtime

After the system calls onCreateOptionsMenu(), it keeps an instance of the menu you populated onCreateOptionsMenu() does not pop up again unless the menu is invalid for some reason. However, you should only use onCreateOptionsMenu() to create the initial menu state and not make changes during the activity lifecycle.

If you want to change the options menu based on events that occur during the activity lifecycle, you can do so in of the onPrepareOptionsMenu() method. This method will pass you the Menu object as it currently exists so that you can change it, e.g. B. Add, remove or disable items. (Fragments also provide an onPrepareOptionsMenu() callback.)

See also: Cost to Develop a Marketplace App Like TaskRabbit

On Android 2.3.x and below, the system calls onPrepareOptionsMenu() each time the user opens the options menu (press the menu key).

p >

On Android 3.0 and above, the options menu is considered to be always open when menu items are displayed in the app bar. When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().

Note: You should never change items in the options menu based on the currently focused view. In touch mode (when the user is not using a trackball or d-pad) views cannot be focused, so you should never use focus as a basis for changing items in the options menu. If you want to provide menu items that are context-sensitive to a view, use a context menu.

Creating context menus

A context menu provides actions that affect a specific item or context frame in the user interface. They can provide a context menu for any view, but they are most commonly used for items in a ListView, GridView, or other collection of views where the user can perform direct actions on any item.

There are two ways, Provide contextual actions:

  • In a floating context menu. A menu is displayed as a floating list of menu items (similar to a dialog box) when the user long clicks (press and hold) on a view that declares support for a context menu. Users can perform one contextual action on one item at a time.
  • In contextual action mode. This mode is a system implementation of ActionMode that displays a contextual action bar at the top of the screen with action items that affect the selected item(s). When this mode is active, users can perform an action on multiple items at the same time (if your app allows it).

Note: Contextual action mode is available on Android 3.0 (API level 11) and higher and is the preferred technique for displaying contextual actions when available. If your app supports versions lower than 3.0, you should use a floating context menu on these devices.

Creating a floating context menu

To provide a floating context menu:

  1. Register the view to associate the context menu with by calling registerForContextMenu() and passing it the view.

    If your activity uses a ListView or GridView and you want each item to provide the same context menu, register all items for a context menu by passing the ListView or GridView to registerForContextMenu().

  2. Implement the onCreateContextMenu() method in your activity or fragment.

    When the registered view receives a long-click event, the system calls your onCreateContextMenu() method. This is where you define the menu items, usually by inflating a menu resource. For example:

    MenuInflater allows you to inflate the context menu of a menu resource. The callback method’s parameters include the View that the user selected and a ContextMenu.ContextMenuInfo object that provides additional information about the selected item. If your activity has multiple views, each providing a different context menu, you can use these parameters to determine which context menu to inflate.

  3. Implement onContextItemSelected().

    When the user selects a menu item, the system calls this method so that you can take the appropriate action.For example:

    The getItemId() method queries the ID for the selected menu item, which you should assign to each menu item in XML using the android:id attribute, as shown in the section on defining a menu in XML .

    If you successfully edit a menu item, return true. If you don’t handle the menu item, you should pass the menu item to the superclass implementation. If your activity contains fragments, the activity will get this callback first. By calling the superclass in the raw state, the system passes the event to the appropriate callback method in each fragment, one at a time (in the order in which each fragment was added) until it returns true or false. (The default implementation for Activity and android.app.Fragment returns false, so you should always call the superclass when not handling it.)

See also  The Complete Guide to a Successful Chiropractic Website

Using the contextual Action mode

Contextual action mode is a system implementation of ActionMode that focuses user interaction on performing contextual actions. When a user activates this mode by selecting an item, a contextual action bar appears at the top of the screen to indicate actions the user can take on the currently selected item(s). While this mode is enabled, the user can select multiple items (if you allow), deselect items, and continue navigating within the activity (if you allow). Action mode is disabled and the contextual action bar disappears when the user deselects all items, presses the BACK button, or selects the Done action on the left side of the bar.

Note: The contextual action bar is not necessarily linked to the app bar. They work independently, although the contextual action bar visually overtakes the app bar’s position.

For views that provide contextual actions, you should typically invoke the contextual action mode on one of two events (or both):

  • The user performs a long click on the view.
  • The user selects a check box or similar UI component within the view.

How your application invokes the contextual action mode and defines the behavior for each action depends on your design. There are basically two designs:

  • For contextual actions on any single view.
  • For batch contextual actions on groups of items in a ListView or GridView (which allows the Allow users to select multiple items and perform an action on all).

The following sections describe the setup required for each scenario.

Enable contextual action mode for individual views

If you only want to invoke the contextual action mode when the user selects certain views, you should:

  1. Implement the ActionMode.Callback interface. In its callback methods, you can specify the actions for the contextual action bar, respond to click events on action items, and handle other action mode lifecycle events.
  2. Call startActionMode() when you want to display the bar (e.g

For example:

  1. Implement the ActionMode.Callback interface:

    Note that these event callbacks are almost exactly the same as the option menu callbacks, except that each of them also passes the ActionMode object associated with the event. You can use ActionMode APIs to make various changes to the CAB such as: B. Revise the title and subtitle with setTitle() and setSubtitle() (useful to indicate how many items are selected).

    Also note that the above example sets the actionMode variable to null when action mode is destroyed. In the next step you will see how it is initialized and how storing the member variables in your activity or fragment can be useful.

  2. Call startActionMode() to use the contextual Activate action mode when needed B. in response to a long click on a view:

    When you call startActionMode(), the system returns the created ActionMode. By storing this in a member variable, you can make changes to the contextual action bar in response to other events. In the example above, ActionMode is used to ensure that the ActionMode instance is not recreated if it is already active, by checking if the member is null before starting the action mode.

Enable contextual batch actions in a ListView or GridView

If you have a collection of items in a ListView or GridView (or another AbsListView extension) and want to allow users to perform batch actions, you should:

  • Implement interface AbsListView.MultiChoiceModeListener and set it for view group with setMultiChoiceModeListener(). In the listener’s callback methods, you can specify the actions for the contextual action bar, respond to click events on action items, and handle other callbacks inherited from the ActionMode.Callback interface.
  • Call setChoiceMode() with on CHOICE_MODE_MULTIPLE_MODAL argument.

For example:

That’s it.Now when the user selects an item with a long click, the system calls the onCreateActionMode() method and displays the contextual action bar with the specified actions. While the contextual action bar is visible, users can select additional items.

In some cases where the contextual actions provide generic action items, you may want to add a checkbox or similar UI element that allows users to do this Select items as they may not recognize the long click behavior. When a user selects the check box, you can invoke contextual action mode by setting the corresponding list item to the checked state with setItemChecked().

Create a popup menu

A popup -Menu is a modal menu anchored to a view. It appears below the anchor view if there is space, or above the view otherwise. It is useful for:

  • Providing an overflow-style menu for actions related to specific content (e.g. Gmail’s email headers, as shown in Figure 4).

    Note: This is not the same as a context menu, which generally applies to actions affecting selected content. For actions affecting selected content, use the contextual action mode or the floating context menu.

  • Providing a second part of a command set (e.g. a button labeled “Add”, which creates a popup menu with various “Add” options).
  • Providing a Spinner-like drop-down menu that does not keep a persistent selection.

Note: PopupMenu is available from API level 11.

See also: Online Fundraising Site: How To Create A Great Website for your Nonprofit

If you define your menu in XML, you can display the popup menu like this:

  1. Instantiate a PopupMenu with its constructor taking the current application context and the view in which to anchor the menu.
  2. Use MenuInflater to inflate your menu resource into the one returned by PopupMenu.getMenu() Inflate menu object.
  3. Call PopupMenu.show().
See also  6 Best Free Website Builder Tools of 2023 Compared

For example, here is a button m with the android:onClick attribute, which displays a popup menu:

The activity can then show the popup menu like this:

In API level 14 and above you can use the two lines that inflate the menu, combine with PopupMenu.inflate().

The menu will be closed when the user selects an item or touches outside the menu area. You can use PopupMenu.OnDismissListener to listen for the dismiss event.

Handle click events

To perform an action when the user selects a menu item, you must implement the PopupMenu.OnMenuItemClickListener interface and register it with your PopupMenu by calling setOnMenuItemclickListener(). When the user selects an item, the system invokes the onMenuItemClick() callback in your UI.

For example:

Creating menu groups

A menu group is a collection of menu items that share certain properties. With a group you can:

  • Show or hide all items with setGroupVisible()
  • Enable or disable all items with setGroupEnabled()
  • Set whether all items are checkable with setGroupCheckable()

You can create a group by nesting elements within a element in your menu resource, or by specifying a group ID specify with add() method.

Here is an example of a menu resource that contains a group:

The items in the Groups appear at the same level as the first item— All three items in the menu are siblings. However, you can change the characteristics of the two items in the group by referencing the group ID and using the methods listed above. The system also never separates grouped articles. For example, if you declare android:showAsAction=”ifRoom” for each item, both will appear in either the action bar or both in the action overflow.

Using checkable menu items

A menu can act as an interface be useful for turning options on and off, using a checkbox for standalone options or radio buttons for groups of mutually exclusive options. Figure 5 shows a submenu with items that can be activated with radio buttons.

Note: Menu items in the icon menu (from the options menu) cannot display check boxes or radio buttons. If you want to make items in the icon menu auditable, you must manually indicate the enabled status by swapping the icon and/or text each time the status changes.

You can define checkable behavior for individual menu items using the android:checkable attribute in the element, or for an entire group using the android:checkableBehavior attribute in the element. For example, all items in this menu group are selectable with a radio button:

The android:checkableBehavior attribute accepts either:

single Only one element from the group can be checked (radio buttons) all All items can be checked (check boxes) none No items can be checked

You can give an item a default checked state by using the android:checked attribute in the element and changing it in the Code using the setChecked() method.

When a checkable item is selected, the system calls your particular item-selected callback method (such as onOptionsItemSelected()). Here you need to set the state of the check box because a check box or radio button does not automatically change its state. You can use isChecked() to query the current status of the item (as it was before the user selected it) and then use setChecked() to set the checked status. For example:

If you don’t set the checked state in this way, the visible state of the item (the check box or radio button) doesn’t change when the user selects it. When you set the status, the activity keeps the item’s enabled status, so the enabled status you set is visible when the user opens the menu later.

Note: Verifiable menu items are for per-session use only and are not saved after the application is destroyed. If you have application settings that you want to save for the user, you should save the data with shared settings.

Add menu items based on an intent

Sometimes you want a menu item to launch a Activity with an intent (regardless of whether it is an activity in your application or another application). If you know the intent you want to use and have a specific menu item you want the intent to trigger, you can use startActivity() to execute the intent during the appropriate on-item selected callback method (e.g. the onOptionsItemSelected() callback).

However, if you are unsure that the user’s device contains an application that handles the intent, adding a menu item that invokes it may result in a non-working menu item because the intent may not is resolved into an activity. To solve this problem, Android allows you to dynamically add menu items to your menu when Android finds activities on the device that process your intent.

How to add menu items based on available activities that have an intent accept:

  1. Define an intent with category CATEGORY_ALTERNATIVE and/or CATEGORY_SELECTED_ALTERNATIVE, plus any other requirements.
  2. Call Menu.addIntentOptions(). Android then searches for applications that can run the intent and adds them to your menu.

If no applications are installed that match the intent, no menu items are added.

Note: CATEGORY_SELECTED_ALTERNATIVE is used to handle the currently selected item on the screen. Therefore, it should only be used when creating a menu in onCreateContextMenu().

For example:

For each found activity that provides an intent filter that matches the defined intent , a menu item is added, using the value in android:label of the intent filter as the menu item title and the application icon as the menu item icon. The addIntentOptions() method returns the number of added menu items.

Note: When you call addIntentOptions(), it overwrites all menu items of the first argument in the specified menu group.

Allow your activity to be added to other menus

You can also offer your activity’s services to other applications, so that your application can be included in the menu of others (reverse the roles described above ).

To be included in other application menus you must define an intent filter as usual, but be sure to include the values ​​CATEGORY_ALTERNATIVE and/or CATEGORY_SELECTED_ALTERNATIVE for the intent filter category . For example:

… …

Read more about writing intent filters in the Intents and Intent Filters document.

See also: How To Make an App? Best Way to Create an App in 8 Steps [2023]

.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button