Mark Murphy - Beginning Android

Здесь есть возможность читать онлайн «Mark Murphy - Beginning Android» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: New York, Год выпуска: 2009, ISBN: 2009, Издательство: Apress, Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Beginning Android: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Beginning Android»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Master Android from first principles and begin the journey toward your own successful Android applications!
Dear Reader,
First, welcome to the world of Android! We’re entering a new era of mobile application development, one marked by open platforms and open source, to take ‘walled gardens’ and make them green houses for any and all to participate in. Android is relatively easy for developers, and I believe that this innovation will help generate a large ecosystem of developers and consumers within a very short time. This means that budding developers such as yourself will have many opportunities to design and build your own applications and you’ll have a huge and hungry customer base.
Second, welcome to the book! Its purpose is to start you on your way with building Android applications, and to help you master the learning curve. Android is already a rich framework, comparable in many ways to the richness Android of desktop Java environments. This means that there is a lot of cool stuff for you to pick up along your journey in order to create the slickest, most useful apps Android you can imagine.
The source code for the code samples in this book is all available from the Apress site, so you can stay as hands-on and practical as you like while I introduce you to the core of Android, and invite you to experiment with the various classes and APIs we’ll be looking at. By the time you’ve finished this book, you’ll be creating your own Android applications and asking yourself what your next great application will be…!
Enjoy! Mark Murphy

Beginning Android — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Beginning Android», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

CHAPTER 11

Applying Menus

Like applications for the desktop and some mobile operating systems, such as Palm OS and Windows Mobile, Android supports activities with application menus. Some Android phones will have a dedicated menu key for popping up the menu; others will offer alternate means for triggering the menu to appear.

Also, as with many GUI toolkits, you can create context menus. On a traditional GUI, this might be triggered by the right mouse button. On mobile devices, context menus typically appear when the user taps-and-holds over a particular widget. For example, if a TextViewhad a context menu and the device was designed for finger-based touch input, you could push the TextViewwith your finger, hold it for a second or two, and a pop-up menu would appear for you to choose from.

Android differs from most other GUI toolkits in terms of menu construction. While you can add items to the menu, you do not have full control over the menu’s contents, nor of the timing of when the menu is built. Part of the menu is system-defined, and that portion is managed by the Android framework itself.

Flavors of Menu

Android considers application menus and context menus to be the options menu and the context menu, respectively. The options menu is triggered by pressing the hardware Menu button on the device, while the context menu is raised by a tap-and-hold on the widget sporting the menu.

In addition, the options menu operates in one of two modes: icon and expanded. When the user first presses the Menu button, the icon mode will appear, showing up to the first six menu choices as large, finger-friendly buttons in a grid at the bottom of the screen. If the menu has more than six choices, the sixth button will become. More — clicking that option will bring up the expanded mode, showing the remaining choices not visible in the regular menu. The menu is scrollable, so the user can get to any of the menu choices.

Menus of Options

Rather than building your activity’s options menu during onCreate(), the way you wire up the rest of your UI, you instead need to implement onCreateOptionsMenu(). This callback receives an instance of Menu.

The first thing you should do is chain upward to the superclass ( super.onCreateOptionsMenu(menu)) so the Android framework can add in any menu choices it feels are necessary. Then you can go about adding your own options, described momentarily.

If you will need to adjust the menu during your activity’s use (e.g., disable a now-invalid menu choice), just hold onto the Menu instance you receive in onCreateOptionsMenu()or implement onPrepareOptionsMenu(), which is called just before displaying the menu each time it is requested.

Given that you have received a Menu object via onCreateOptionsMenu(), you add menu choices by calling add(). There are many flavors of this method, which require some combination of the following parameters:

• A group identifier ( int), which should be NONE unless you are creating a specific grouped set of menu choices for use with setGroupCheckable()(see the following list).

• A choice identifier (also an int) for use in identifying this choice in the onOptionsItemSelected()callback when a menu choice is selected.

• An order identifier (yet another int), for indicating where this menu choice should be slotted if the menu has Android-supplied choices alongside your own — for now, just use NONE.

• The text of the menu choice, as a Stringor a resource ID.

The add()family of methods all return an instance of MenuItem, where you can adjust any of the menu-item settings you have already set (e.g., the text of the menu choice). You can also set the shortcuts for the menu choice — single-character mnemonics that select that menu choice when the menu is visible. Android supports both an alphabetic (or QWERTY) set of shortcuts and a numeric set of shortcuts. These are set individually by calling setAlphabeticShortcut()and setNumericShortcut(), respectively. The menu is placed into alphabetic shortcut mode by calling setQwertyMode()on the menu with a trueparameter.

The choice and group identifiers are keys used to unlock additional menu features, such as these:

• Calling MenuItem#setCheckable()with a choice identifier to control if the menu choice has a two-state checkbox alongside the title, where the checkbox value gets toggled when the user chooses that menu choice

• Calling Menu#setGroupCheckable()with a group identifier to turn a set of menu choices into ones with a mutual-exclusion radio button between them, so one out of the group can be in the “checked” state at any time

You can also call addIntentOptions()to populate the menu with menu choices corresponding to the available activities for an intent (see Chapter 25).

Finally, you can create fly-out sub-menus by calling addSubMenu()and supplying the same parameters as addMenu(). Android will eventually call onCreatePanelMenu(), passing it the choice identifier of your sub-menu, along with another Menuinstance representing the sub-menu itself. As with onCreateOptionsMenu(), you should chain upward to the superclass, then add menu choices to the sub-menu. One limitation is that you cannot indefinitely nest sub-menus — a menu can have a sub-menu, but a sub-menu cannot itself have a sub-sub-menu.

If the user makes a menu choice, your activity will be notified via the onOptionsItemSelected()callback that a menu choice was selected. You are given the MenuItemobject corresponding to the selected menu choice. A typical pattern is to switch()on the menu ID ( item.getItemId()) and take appropriate action. Note that onOptionsItemSelected()is used regardless of whether the chosen menu item was in the base menu or in a sub-menu.

Menus in Context

By and large, context menus use the same guts as option menus. The two main differences are how you populate the menu and how you are informed of menu choices.

First you need to indicate which widget(s) on your activity have context menus. To do this, call registerForContextMenu()from your activity, supplying the Viewthat is the widget in need of a context menu.

Next you need to implement onCreateContextMenu(), which, among other things, is passed the Viewyou supplied in registerForContextMenu(). You can use that to determine which menu to build, assuming your activity has more than one.

The onCreateContextMenu()method gets the ContextMenuitself, the Viewthe context menu is associated with, and a ContextMenu.ContextMenuInfo, which tells you which item in the list the user did the tap-and-hold over, in case you want to customize the context menu based on that information. For example, you could toggle a checkable menu choice based on the current state of the item.

It is also important to note that onCreateContextMenu()gets called each time the context menu is requested. Unlike the options menu (which is built only once per activity), context menus are discarded once they are used or dismissed. Hence, you do not want to hold onto the supplied ContextMenuobject; just rely on getting the chance to rebuild the menu to suit your activity’s needs on demand based on user actions.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Beginning Android»

Представляем Вашему вниманию похожие книги на «Beginning Android» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Beginning Android»

Обсуждение, отзывы о книге «Beginning Android» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x