action bar что это

ActionBar на Android 2.1+ с помощью Support Library. Часть 3 — Полезные функции

Всем доброго времени суток!

Мда, давно не писал я статей на Хабр. Что ж, буду это дело исправлять.
Вообще, ActionBar в Android – довольно сложная штука. В первой и второй частях я рассмотрел только основные его функции – меню и навигация. Но есть ведь и множество дополнительных: Split ActionBar, кастомный View для элемента меню и ActionProvider. О них и пойдёт речь. Кроме того, бонус: многие знают, что кнопка Up служит для перехода на предыдущее Activity. Но если на экран можно попасть только с одной другой Activity, то можно не кодить переход вверх. Заинтригованы? Прошу под кат.

Split ActionBar

action bar что это

Split ActionBar – это полоска внизу экрана с элементами меню. Он может быть использован, если в основном ActionBar не хватает места (в середине), или он отсутствует (справа). Добавить его легко: достаточно в файле манифеста добавить для Activity или всего приложения следующие строки:

Чтобы убрать верхний ActionBar (как на рисунке справа) нужно вызвать методы ActionBar setDisplayShowHomeEnabled(false) и setDisplayShowTitleEnabled(false).

ActionView

В пространстве имён android в старых версиях нет этих атрибутов, поэтому нужно использовать пространство имён Support Library – для этого добавляем строчку xmlns:yourapp=«schemas.android.com/apk/res-auto» и используем атрибут yourapp:actionViewClass. Программно изменить разметку MenuItem’a можно с помощью методов MenuItemCompat setActionView(MenuItem item, int resId) и setActionView(MenuItem item, View view), получить текущий View – getActionView(MenuItem item).

Один из примеров ActionView – SearchView, о нём подробнее написано здесь.

Action Provider

action bar что это

ActionProvider имеет много общего с ActionView. Он также заменяет кнопку на собственный layout, но может показывать выпадающий список и контролировать поведение элемента меню. Чтобы задать его для пункта меню, достаточно для тега добавить атрибут actionProviderClass, куда записать адрес вашего класса. Он должен наследоваться от ActionProvider и переопределять следующие методы:
-ActionProvider(Context context) –конструктор, принимает на вход контекст, который нужно сохранить в поле класса для использования в других методах;
-onCreateActionView(MenuItem) – здесь создаём вьюшку для элемента меню с помощью LayoutInflater, полученного из контекста, и возвращаем её;
-onPerformDefaultAction() – вызывается, когда пользователь нажимает на пункт в ActionBar.

Если вы используете ActionProvider, то НЕ должны обрабатывать нажатия на него в onOptionsItemSelected(), ну или возвращать там false, потому что иначе onPerformDefaultAction() не будет вызван.

Если ваш ActionProvider показывает подменю, то нужно переопределить его метод hasSubMenu() и возвращать true. Тогда вместо onPerformDefaultAction() будет вызван onPrepareSubMenu (SubMenu subMenu). Там создаёте или изменяете подменю.

ShareActionProvider

В Android есть свой ActionProvider для отправки контента – ShareActionProvider. Когда создаём меню с ним, необходимо в методе onCreateOptionsMenu получить его экземпляр с помощью MenuItemCompat.getActionProvider(MenuItem) и вызвать setShareIntent(), куда передать Intent с ACTION_SEND и прикреплённым контентом:

Так как контент на экране может изменяться (например, перелистывание картинок), то нужно вызывать setShareIntent() каждый раз, когда контент меняется.

Родительская Activity

Если на экран в приложении можно попасть только с ОДНОЙ другой Activity, то имеет смысл настроить автоматический переход на неё по нажатию кнопки Up в ActionBar. Сделать это очень просто: в файле манифеста для нужной Activity добавить строки:

Напомню, чтобы кнопка Home работала как Up, вызовите методы SupportActionBar setHomeButtonEnabled(true) и setDisplayHomeAsUpEnabled(true).

Вся информация взята отсюда (официальный гайдлайн на английском).

Часть 1 — Добавление Support Library в проект, простой пример, поиск
Часть 2 — Навигация с помощью вкладок и выпадающего списка

Источник

Переводим ActionBar на следующий уровень

Будучи на Google I/O, я наконец нашел приложение, использующее в ActionBar технику анимации. Давайте будем честными, это буквально взорвало мой взгляд когда я в первый раз это увидел. Я влюбился в хороший, тонкий и чрезвычайно полезный анимационный эффект, и, вероятно, даже больше, чем в само приложение! Я уверен, вы знаете приложение о котором я говорю, так как оно было представлено во время Google I/O. Это приложение Play Music!

Темы и стили для приложения

Логично, что стиль ActionBar определен в values/styles.xml следующим образом:
values/styles.xml

В заключение, мы должны использовать данную тему, чтобы применить этот стиль к нашей Activity :
AndroidManifest.xml

Обратите внимание, что с помощью тем и стилей мы удаляем все потенциальные проблемы мерцания при запуске (см. «Правильно сделанный запуск Android-приложения» для получения дополнительной информации).

Получение готового содержания

Как я пояснил ранее, затухание ActionBar синхронизировано на попиксельным состоянии контейнера прокрутки. В этом примере мы просто будем использовать ScrollView как контейнер прокрутки. Одним из основных недостатков этого контейнера является то, что вы не можете зарегистрировать слушателя для того, чтобы получать уведомления, когда состояние прокрутки изменилось. Но это можно легко обойти, создав NotifyingScrollView унаследованный от оригинального ScrollView :
NotifyingScrollView.java

Теперь мы можем использовать этот новый контейнер прокрутки в нашем XML-макете:
layout/activity_home.xml

Показываем\скрываем ActionBar

Вы уже можете запустить код. Хотя результат выглядит также как и в анимации приложения Play Music, мы можем продолжить дорабатывать его, чтобы сделать ещё лучше.

Источник

Разбираемся с ActionBar(App Bar) и AppCompatActivity

action bar что это

Вот так выглядит приложение без ActionBar (API level 7).

action bar что это

А вот так выглядит приложение с ActionBar (API level 7) при помощи AppCompatActivity и Support Library release 23.

action bar что это

ActionBar появился в Android 3.0 (API level 11), и стал отображаться в верхней части окна Activity, при использовании темы Holo или одной из ее тем-потомков.

Для получения дополнительной информации по Action Bar прочитайте документацию тут ActionBar API level 11 и тут ActionBar Support Library 23.0.0

Начиная с Android L (API level 21), ActionBar, в application layout, может быть представлен виджетом Toolbar.

Поддержка ActionBar в старых версиях Android начиная с API level 7 осуществляется с помощью AppCompatActivity.

Для того, чтобы добавить поддержку ActionBar в старых версиях Android, нам нужно расширить наш главный класс MainActivity от AppCompatActivity.

Так же нам нужно импортировать (v7 appcompat library) библиотеку поддержки 7-ой версии.

Весь код файла MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity <
@Override
protected void onCreate(Bundle savedInstanceState) <
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
>
>

Но для того, что бы добавить библеотеку поддержки в наш проект, нам нужно в файле build.gradle в разделе dependencies иметь следующую запись

action bar что это



Внимание! Начиная с Support Library release 26.0.0 (July 2017), минимальная версия API Level увеличилась до Android 4.0 (API level 14). То есть, если мы хотим использовать Support Library версии 26 и выше, то при компиляции файла apk, минимальная версия SDK теперь должна быть 14.

Для того, что бы посмотреть, что добавили или исправили в новом релизе Support Library нажимаем тут.

Источник

Кастомизация виджета Action Bar

action bar что этоСтатья является переводом топика из блога android-developers. В ней показывается, как стилизовать виджет Action Bar нужным вам образом. В качестве примера рассматривается изменение оформления виджета под общую цветовую гамму вышеописанного блога.

Со времени появления паттерна Action Bar прошло уже немало времени, и многие разработчики уже внедрили его в свои приложения. В Android 3.0 (Honeycomb) данный паттерн вообще является частью SDK и общей навигационной парадигмы. Использование общепринятого элемента навигации упрощает освоение программы пользователем (потому что он, скорее всего, уже работал с ним), и не требует от разработчика придумывать свои собственные «велосипеды». Но раз уж все используют один и тот же паттерн, то, ясное дело, каждый стилизует его под своё приложение. Следующий пример показывает, как стилизовать Action Bar под общий вид/имидж приложения. Будем изменять стандартную тему оформления Holo.Light для соответствия блогу android-developers.

Иконка

Для создания иконки в выбранной цветовой схеме можно использовать Android Asset Studio. Будем использовать это изображение, как логотип.

action bar что это

Навигация

Далее, секция навигации работает в трёх разных режимах. Рассмотрим их по очереди.

Стандартный

Стандартный режим просто отображает название Activity. Для этого стилизация не нужна, поехали дальше.

Список

Слева — стандартный выпадающий список, справа — тот эффект, который нам нужен.

action bar что это

В стандартном списке используется цветовая схема, в которой доминирует голубой цвет. Чтобы реализовать нужную нам схему, перегрузим android:actionDropDownStyle

В этом xml-файле для оформления подсветки, спиннера и верхнего bar’a используется комбинация state-list’ов и nine-patch изображений.

Вкладки

Ниже расположены скриншоты оформления вкладок «до» и «после».

action bar что это

И снова, в стандартной тема для вкладок доминирует голубой цвет. Для переоформления перегрузим android:actionBarTabStyle.

Действия (Actions)

И снова, «до» и «после».
action bar что это

При выделении того или иного, элемента он подсвечивается голубым. Для изменения, перегрузим android:selectableItemBackground.

Также, меню при расширении показывает голубой прямоугольник наверху списка. Для изменения перегрузим android:popupMenuStyle.

Также изменим цвет выделенных элементов в меню.

Кроме этого еще нужно изменить оформление чекбоксов и radio buttons.

action bar что это

В принципе, можно также изменить фон. По умолчанию, в теме Holo.Light он прозрачный. Для изменения нужно перегрузить android:actionBarStyle.

Соединяем всё вместе

Для объединения всех элементов, создадим кастомный стиль.

Теперь можно применять этот стиль оформления к какому-либо Activity или всему приложению.

Важно еще отметить, что некоторые стили, которые мы перегрузили, действуют на все виджеты (например android:selectableItemBackground). То есть, мы таким образом изменяем оформление всего приложения, что бывает весьма полезно, если вы стараетесь выдержать общий стиль.

Источник

Action Bar

Design Guide

In this document

Key classes

The action bar is a window feature that identifies the user location, and provides user actions and navigation modes. Using the action bar offers your users a familiar interface across applications that the system gracefully adapts for different screen configurations.

action bar что это

Figure 1. An action bar that includes the [1] app icon, [2] two action items, and [3] action overflow.

The action bar provides several key functions:

For more information about the action bar’s interaction patterns and design guidelines, see the Action Bar design guide.

The ActionBar APIs were first added in Android 3.0 (API level 11) but they are also available in the Support Library for compatibility with Android 2.1 (API level 7) and above.

This guide focuses on how to use the support library’s action bar, but if your app supports only Android 3.0 or higher, you should use the ActionBar APIs in the framework. Most of the APIs are the same—but reside in a different package namespace—with a few exceptions to method names or signatures that are noted in the sections below.

Caution: Be certain you import the ActionBar class (and related APIs) from the appropriate package:

Note: If you’re looking for information about the contextual action bar for displaying contextual action items, see the Menu guide.

Adding the Action Bar

As mentioned above, this guide focuses on how to use the ActionBar APIs in the support library. So before you can add the action bar, you must set up your project with the appcompat v7 support library by following the instructions in the Support Library Setup.

Once your project is set up with the support library, here’s how to add the action bar:

Now your activity includes the action bar when running on Android 2.1 (API level 7) or higher.

On API level 11 or higher

Removing the action bar

On API level 11 or higher

Get the ActionBar with the getActionBar() method.

Using a logo instead of an icon

By default, the system uses your application icon in the action bar, as specified by the icon attribute in the or element. However, if you also specify the logo attribute, then the action bar uses the logo image instead of the icon.

A logo should usually be wider than the icon, but should not include unnecessary text. You should generally use a logo only when it represents your brand in a traditional format that users recognize. A good example is the YouTube app’s logo—the logo represents the expected user brand, whereas the app’s icon is a modified version that conforms to the square requirement for the launcher icon.

Adding Action Items

action bar что это

Figure 2. Action bar with three action buttons and the overflow button.

The action bar provides users access to the most important action items relating to the app’s current context. Those that appear directly in the action bar with an icon and/or text are known as action buttons. Actions that can’t fit in the action bar or aren’t important enough are hidden in the action overflow. The user can reveal a list of the other actions by pressing the overflow button on the right side (or the device Menu button, if available).

When your activity starts, the system populates the action items by calling your activity’s onCreateOptionsMenu() method. Use this method to inflate a menu resource that defines all the action items. For example, here’s a menu resource defining a couple of menu items:

Then in your activity’s onCreateOptionsMenu() method, inflate the menu resource into the given Menu to add each item to the action bar:

To request that an item appear directly in the action bar as an action button, include showAsAction=»ifRoom» in the tag. For example:

If there’s not enough room for the item in the action bar, it will appear in the action overflow.

Using XML attributes from the support library

Notice that the showAsAction attribute above uses a custom namespace defined in the tag. This is necessary when using any XML attributes defined by the support library, because these attributes do not exist in the Android framework on older devices. So you must use your own namespace as a prefix for all attributes defined by the support library.

If your menu item supplies both a title and an icon—with the title and icon attributes—then the action item shows only the icon by default. If you want to display the text title, add «withText» to the showAsAction attribute. For example:

Note: The «withText» value is a hint to the action bar that the text title should appear. The action bar will show the title when possible, but might not if an icon is available and the action bar is constrained for space.

You should always define the title for each item even if you don’t declare that the title appear with the action item, for the following reasons:

The icon is optional, but recommended. For icon design recommendations, see the Iconography design guide. You can also download a set of standard action bar icons (such as for Search or Discard) from the Downloads page.

You can also use «always» to declare that an item always appear as an action button. However, you should not force an item to appear in the action bar this way. Doing so can create layout problems on devices with a narrow screen. It’s best to instead use «ifRoom» to request that an item appear in the action bar, but allow the system to move it into the overflow when there’s not enough room. However, it might be necessary to use this value if the item includes an action view that cannot be collapsed and must always be visible to provide access to a critical feature.

Handling clicks on action items

Note: If you inflate menu items from a fragment, via the Fragment class’s onCreateOptionsMenu() callback, the system calls onOptionsItemSelected() for that fragment when the user selects one of those items. However, the activity gets a chance to handle the event first, so the system first calls onOptionsItemSelected() on the activity, before calling the same callback for the fragment. To ensure that any fragments in the activity also have a chance to handle the callback, always pass the call to the superclass as the default behavior instead of returning false when you do not handle the item.

action bar что это

Figure 3. Mock-ups showing an action bar with tabs (left), then with split action bar (middle); and with the app icon and title disabled (right).

Using split action bar

Split action bar provides a separate bar at the bottom of the screen to display all action items when the activity is running on a narrow screen (such as a portrait-oriented handset).

Separating the action items this way ensures that a reasonable amount of space is available to display all your action items on a narrow screen, while leaving room for navigation and title elements at the top.

To enable split action bar when using the support library, you must do two things:

Navigating Up with the App Icon

Design Guide

Navigation with Back and Up

action bar что это

Figure 4. The Up button in Gmail.

Enabling the app icon as an Up button allows the user to navigate your app based on the hierarchical relationships between screens. For instance, if screen A displays a list of items, and selecting an item leads to screen B, then screen B should include the Up button, which returns to screen A.

Note: Up navigation is distinct from the back navigation provided by the system Back button. The Back button is used to navigate in reverse chronological order through the history of screens the user has recently worked with. It is generally based on the temporal relationships between screens, rather than the app’s hierarchy structure (which is the basis for up navigation).

Now the icon in the action bar appears with the Up caret (as shown in figure 4). However, it won’t do anything by default. To specify the activity to open when the user presses Up button, you have two options:

This is the best option when the parent activity is always the same. By declaring in the manifest which activity is the parent, the action bar automatically performs the correct action when the user presses the Up button.

Beginning in Android 4.1 (API level 16), you can declare the parent with the parentActivityName attribute in the element.

This is appropriate when the parent activity may be different depending on how the user arrived at the current screen. That is, if there are many paths that the user could have taken to reach the current screen, the Up button should navigate backward along the path the user actually followed to get there.

The system calls getSupportParentActivityIntent() when the user presses the Up button while navigating your app (within your app’s own task). If the activity that should open upon up navigation differs depending on how the user arrived at the current location, then you should override this method to return the Intent that starts the appropriate parent activity.

The system calls onCreateSupportNavigateUpTaskStack() for your activity when the user presses the Up button while your activity is running in a task that does not belong to your app. Thus, you must use the TaskStackBuilder passed to this method to construct the appropriate back stack that should be synthesized when the user navigates up.

Even if you override getSupportParentActivityIntent() to specify up navigation as the user navigates your app, you can avoid the need to implement onCreateSupportNavigateUpTaskStack() by declaring «default» parent activities in the manifest file as shown above. Then the default implementation of onCreateSupportNavigateUpTaskStack() will synthesize a back stack based on the parent activities declared in the manifest.

For more information about implementing Up navigation, read Providing Up Navigation.

Adding an Action View

action bar что это

An action view is a widget that appears in the action bar as a substitute for an action button. An action view provides fast access to rich actions without changing activities or fragments, and without replacing the action bar. For example, if you have an action for Search, you can add an action view to embeds a SearchView widget in the action bar, as shown in figure 5.

To declare an action view, use either the actionLayout or actionViewClass attribute to specify either a layout resource or widget class to use, respectively. For example, here’s how to add the SearchView widget:

Notice that the showAsAction attribute also includes the «collapseActionView» value. This is optional and declares that the action view should be collapsed into a button. (This behavior is explained further in the following section about Handling collapsible action views.)

On API level 11 or higher

Get the action view by calling getActionView() on the corresponding MenuItem :

For more information about using the search widget, see Creating a Search Interface.

Handling collapsible action views

To preserve the action bar space, you can collapse your action view into an action button. When collapsed, the system might place the action into the action overflow, but the action view still appears in the action bar when the user selects it. You can make your action view collapsible by adding «collapseActionView» to the showAsAction attribute, as shown in the XML above.

The system also collapses your action view when the user presses the Up button or Back button.

Adding an Action Provider

action bar что это

Figure 6. An action bar with ShareActionProvider expanded to show share targets.

Similar to an action view, an action provider replaces an action button with a customized layout. However, unlike an action view, an action provider takes control of all the action’s behaviors and an action provider can display a submenu when pressed.

Because each ActionProvider class defines its own action behaviors, you don’t need to listen for the action in the onOptionsItemSelected() method. If necessary though, you can still listen for the click event in the onOptionsItemSelected() method in case you need to simultaneously perform another action. But be sure to return false so that the the action provider still receives the onPerformDefaultAction() callback to perform its intended action.

However, if the action provider provides a submenu of actions, then your activity does not receive a call to onOptionsItemSelected() when the user opens the list or selects one of the submenu items.

Using the ShareActionProvider

Now the action provider takes control of the action item and handles both its appearance and behavior. But you must still provide a title for the item to be used when it appears in the action overflow.

The only thing left to do is define the Intent you want to use for sharing. To do so, edit your onCreateOptionsMenu() method to call MenuItemCompat.getActionProvider() and pass it the MenuItem holding the action provider. Then call setShareIntent() on the returned ShareActionProvider and pass it an ACTION_SEND intent with the appropriate content attached.

The ShareActionProvider now handles all user interaction with the item and you do not need to handle click events from the onOptionsItemSelected() callback method.

Note: Although the ShareActionProvider ranks share targets based on frequency of use, the behavior is extensible and extensions of ShareActionProvider can perform different behaviors and ranking based on the history file (if appropriate).

Creating a custom action provider

To create your own action provider for a different action, simply extend the ActionProvider class and implement its callback methods as appropriate. Most importantly, you should implement the following:

However, if your action provider provides a submenu, through the onPrepareSubMenu() callback, then the submenu appears even when the action provider is placed in the action overflow. Thus, onPerformDefaultAction() is never called when there is a submenu.

Adding Navigation Tabs

action bar что это

Figure 7. Action bar tabs on a wide screen.

Design Guide

Also read

Creating Swipe Views with Tabs

action bar что это

Figure 8. Tabs on a narrow screen.

Tabs in the action bar make it easy for users to explore and switch between different views in your app. The tabs provided by the ActionBar are ideal because they adapt to different screen sizes. For example, when the screen is wide enough the tabs appear in the action bar alongside the action buttons (such as when on a tablet, shown in figure 7), while when on a narrow screen they appear in a separate bar (known as the «stacked action bar», shown in figure 8). In some cases, the Android system will instead show your tab items as a drop-down list to ensure the best fit in the action bar.

To get started, your layout must include a ViewGroup in which you place each Fragment associated with a tab. Be sure the ViewGroup has a resource ID so you can reference it from your code and swap the tabs within it.

Once you determine where the fragments appear in the layout, the basic procedure to add tabs is:

Notice that the ActionBar.TabListener callback methods don’t specify which fragment is associated with the tab, but merely which ActionBar.Tab was selected. You must define your own association between each ActionBar.Tab and the appropriate Fragment that it represents. There are several ways you can define the association, depending on your design.

For example, here’s how you might implement the ActionBar.TabListener such that each tab uses its own instance of the listener:

Caution: You must not call commit() for the fragment transaction in each of these callbacks—the system calls it for you and it may throw an exception if you call it yourself. You also cannot add these fragment transactions to the back stack.

In this example, the listener simply attaches ( attach() ) a fragment to the activity layout—or if not instantiated, creates the fragment and adds ( add() ) it to the layout (as a child of the android.R.id.content view group)—when the respective tab is selected, and detaches ( detach() ) it when the tab is unselected.

For example, the following code adds two tabs using the listener defined above:

Caution: It’s important that you save the state of each fragment so when users switch fragments with the tabs and then return to a previous fragment, it looks the way it did when they left. Some of the state is saved by default, but you may need to manually save state for customized views. For information about saving the state of your fragment, see the Fragments API guide.

Note: The above implementation for ActionBar.TabListener is one of several possible techniques. Another popular option is to use ViewPager to manage the fragments so users can also use a swipe gesture to switch tabs. In this case, you simply tell the ViewPager the current tab position in the onTabSelected() callback. For more information, read Creating Swipe Views with Tabs.

Adding Drop-down Navigation

action bar что это

Figure 9. A drop-down navigation list in the action bar.

As another mode of navigation (or filtering) for your activity, the action bar offers a built in drop-down list (also known as a «spinner»). For example, the drop-down list can offer different modes by which content in the activity is sorted.

Using the drop-down list is useful when changing the content is important but not necessarily a frequent occurrence. In cases where switching the content is more frequent, you should use navigation tabs instead.

The basic procedure to enable drop-down navigation is:

This procedure is relatively short, but implementing the SpinnerAdapter and ActionBar.OnNavigationListener is where most of the work is done. There are many ways you can implement these to define the functionality for your drop-down navigation and implementing various types of SpinnerAdapter is beyond the scope of this document (you should refer to the SpinnerAdapter class reference for more information). However, below is an example for a SpinnerAdapter and ActionBar.OnNavigationListener to get you started (click the title to reveal the sample).

A string array defined in a resource looks like this:

In this example, when the user selects an item from the drop-down list, a fragment is added to the layout (replacing the current fragment in the R.id.fragment_container view). The fragment added is given a tag that uniquely identifies it, which is the same string used to identify the fragment in the drop-down list.

Here’s a look at the ListContentFragment class that defines each fragment in this example:

Styling the Action Bar

If you want to implement a visual design that represents your app’s brand, the action bar allows you to customize each detail of its appearance, including the action bar color, text colors, button styles, and more. To do so, you need to use Android’s style and theme framework to restyle the action bar using special style properties.

Caution: For all background drawables you provide, be sure to use Nine-Patch drawables to allow stretching. The nine-patch image should be smaller than 40dp tall and 30dp wide.

General appearance

Supported styles include:

background Defines a drawable resource for the action bar background. backgroundStacked Defines a drawable resource for the stacked action bar (the tabs). backgroundSplit Defines a drawable resource for the split action bar. actionButtonStyle Defines a style resource for action buttons.

actionOverflowButtonStyle Defines a style resource for overflow action items.

displayOptions Defines one or more action bar display options, such as whether to use the app logo, show the activity title, or enable the Up action. See displayOptions for all possible values. divider Defines a drawable resource for the divider between action items. titleTextStyle Defines a style resource for the action bar title.

windowActionBarOverlay Declares whether the action bar should overlay the activity layout rather than offset the activity’s layout position (for example, the Gallery app uses overlay mode). This is false by default.

Normally, the action bar requires its own space on the screen and your activity layout fills in what’s left over. When the action bar is in overlay mode, your activity layout uses all the available space and the system draws the action bar on top. Overlay mode can be useful if you want your content to keep a fixed size and position when the action bar is hidden and shown. You might also like to use it purely as a visual effect, because you can use a semi-transparent background for the action bar so the user can still see some of your activity layout behind the action bar.

Note: The Holo theme families draw the action bar with a semi-transparent background by default. However, you can modify it with your own styles and the DeviceDefault theme on different devices might use an opaque background by default.

When overlay mode is enabled, your activity layout has no awareness of the action bar lying on top of it. So, you must be careful not to place any important information or UI components in the area overlaid by the action bar. If appropriate, you can refer to the platform’s value for actionBarSize to determine the height of the action bar, by referencing it in your XML layout. For example:

Action items

actionBarItemBackground Defines a drawable resource for each action item’s background. This should be a state-list drawable to indicate different selected states. itemBackground Defines a drawable resource for each action overflow item’s background. This should be a state-list drawable to indicate different selected states. actionBarDivider Defines a drawable resource for the divider between action items. actionMenuTextColor Defines a color for text that appears in an action item. actionMenuTextAppearance Defines a style resource for text that appears in an action item. actionBarWidgetTheme Defines a theme resource for widgets that are inflated into the action bar as action views.

Navigation tabs

actionBarTabBarStyle Defines a style resource for the thin bar that appears below the navigation tabs.

actionBarTabTextStyle Defines a style resource for text in the navigation tabs.

Drop-down lists

Example theme

Notice that there are two versions for each action bar style property. The first one includes the android: prefix on the property name to support API levels 11 and higher that include these properties in the framework. The second version does not include the android: prefix and is for older versions of the platform, on which the system uses the style property from the support library. The effect for each is the same.

In your manifest file, you can apply the theme to your entire app:

Or to individual activities:

Caution: Be certain that each theme and style declares a parent theme in the tag, from which it inherits all styles not explicitly declared by your theme. When modifying the action bar, using a parent theme is important so that you can simply override the action bar styles you want to change without re-implementing the styles you want to leave alone (such as text size or padding in action items).

For more information about using style and theme resources in your application, read Styles and Themes.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *