Menu item intents

If you've read the Application Fundamentals, then you're at least a little familiar with Android Intents. These allow applications to bind with each other, share information, and perform user tasks cooperatively. Just like your application might fire an Intent to launch a web browser, an email client, or another Activity in your application, you can perform such actions from within a menu. There are two ways to do this: define an Intent and assign it to a single menu item, or define an Intent and allow Android to search the device for activities and dynamically add a menu item for each one that meets the Intent criteria.

For example, inside the onCreateOptionsMenu() method, you can define a new menu item with an Intent like this:

MenuItem menuItem = menu.add(0, PHOTO_PICKER_ID, 0, "Select Photo"); menuItem.setIntent(new Intent(this, PhotoPicker.class));

Android will automatically launch the Activity when the item is selected.

Note: This will not return a result to your Activity. If you wish to be returned a result, then do not use setIntent() . Instead, handle the selection as usual in the onOptionsMenuItemSelected() or onContextMenuItemSelected() callback and call startActivityForResult() .

0 0

Post a comment