Replacing the Action Bar
One of the most common uses for the Toolbar is to replace the default action bar with a custom Toolbar (when a new Android project is created, it uses the default action bar). Because the Toolbar provides the ability to add branded logos, titles, menu items, navigation buttons, and even custom views to the app bar section of an Activity’s UI, it offers a significant upgrade over the default action bar.
To replace an app’s default action bar with a Toolbar :
- Create a new custom theme and modify the app’s properties so that it uses this new theme.
- Disable the windowActionBar attribute in the custom theme and enable the windowNoTitle attribute.
- Define a layout for the Toolbar .
- Include the Toolbar layout in the Activity’s Main.axml layout file.
- Add code to the Activity’s OnCreate method to locate the Toolbar and call SetActionBar to install the ToolBar as the action bar.
The following sections explain this process in detail. A simple app is created and its action bar is replaced with a customized Toolbar .
Start an App Project
Create a new Android project called ToolbarFun (see Hello, Android for more information about creating a new Android project). After this project is created, set the target and minimum Android API levels to Android 5.0 (API Level 21 — Lollipop) or later. For more information about setting Android version levels, see Understanding Android API Levels. When the app is built and run, it displays the default action bar as seen in this screenshot:
Create a Custom Theme
Open the Resources/values directory and a create a new file called styles.xml. Replace its contents with the following XML:
This XML defines a new custom theme called MyTheme that is based on the Theme.Material.Light.DarkActionBar theme in Lollipop. The windowNoTitle attribute is set to true to hide the title bar:
- true
To display the custom toolbar, the default ActionBar must be disabled:
- false
An olive-green colorPrimary setting is used for the background color of the toolbar:
- #5A8622
Apply the Custom Theme
Edit Properties/AndroidManifest.xml and add the following android:theme attribute to the element so that the app uses the MyTheme custom theme:
For more information about applying a custom theme to an app, see Using Custom Themes.
Define a Toolbar Layout
In the Resources/layout directory, create a new file called toolbar.xml. Replace its contents with the following XML:
This XML defines the custom Toolbar that replaces the default action bar. The minimum height of the Toolbar is set to the size of the action bar that it replaces:
android:minHeight="?android:attr/actionBarSize"
The background color of the Toolbar is set to the olive-green color defined earlier in styles.xml:
android:background="?android:attr/colorPrimary"
Beginning with Lollipop, the android:theme attribute can be used to style an individual view. The ThemeOverlay.Material themes introduced in Lollipop make it possible to overlay the default Theme.Material themes, overwriting relevant attributes to make them either light or dark. In this example, the Toolbar uses a dark theme so that its contents are light in color:
android:theme="@android:style/ThemeOverlay.Material.Dark.ActionBar"
This setting is used so that menu items contrast with the darker background color.
Include the Toolbar Layout
Edit the layout file Resources/layout/Main.axml and replace its contents with the following XML:
This layout includes the Toolbar defined in toolbar.xml and uses a RelativeLayout to specify that the Toolbar is to be placed at the very top of the UI (above the button).
Find and Activate the Toolbar
Edit MainActivity.cs and add the following using statement:
using Android.Views;
Also, add the following lines of code to the end of the OnCreate method:
var toolbar = FindViewById(Resource.Id.toolbar); SetActionBar(toolbar); ActionBar.Title = "My Toolbar";
This code finds the Toolbar and calls SetActionBar so that the Toolbar will take on default action bar characteristics. The title of the Toolbar is changed to My Toolbar. As seen in this code example, the ToolBar can be directly referenced as an action bar. Compile and run this app – the customized Toolbar is displayed in place of the default action bar:
Notice that the Toolbar is styled independently of the Theme.Material.Light.DarkActionBar theme that is applied to the remainder of the app.
If an exception occurs while running the app, see the Troubleshooting section below.
Add Menu Items
In this section, menus are added to the Toolbar . The upper right area of the ToolBar is reserved for menu items – each menu item (also called an action item) can perform an action within the current activity or it can perform an action on behalf of the entire app.
To add menus to the Toolbar :
- Add menu icons (if required) to the mipmap- folders of the app project. Google provides a set of free menu icons on the Material icons page.
- Define the contents of the menu items by adding a new menu resource file under Resources/menu.
- Implement the OnCreateOptionsMenu method of the Activity – this method inflates the menu items.
- Implement the OnOptionsItemSelected method of the Activity – this method performs an action when a menu item is tapped.
The following sections demonstrate this process in detail by adding Edit and Save menu items to the customized Toolbar .
Install Menu Icons
Continuing with the ToolbarFun example app, add menu icons to the app project. Download toolbar icons, unzip, and copy the contents of the extracted mipmap- folders to the project mipmap- folders under ToolbarFun/Resources and include each added icon file in the project.
Define a Menu Resource
Create a new menu subdirectory under Resources. In the menu subdirectory, create a new menu resource file called top_menus.xml and replace its contents with the following XML:
This XML creates three menu items:
- An Edit menu item that uses the ic_action_content_create.png icon (a pencil).
- A Save menu item that uses the ic_action_content_save.png icon (a diskette).
- A Preferences menu item that does not have an icon.
The showAsAction attributes of the Edit and Save menu items are set to ifRoom – this setting causes these menu items to appear in the Toolbar if there is sufficient room for them to be displayed. The Preferences menu item sets showAsAction to never – this causes the Preferences menu to appear in the overflow menu (three vertical dots).
Implement OnCreateOptionsMenu
Add the following method to MainActivity.cs:
public override bool OnCreateOptionsMenu(IMenu menu)
Android calls the OnCreateOptionsMenu method so that the app can specify the menu resource for an activity. In this method, the top_menus.xml resource is inflated into the passed menu . This code causes the new Edit, Save, and Preferences menu items to appear in the Toolbar .
Implement OnOptionsItemSelected
Add the following method to MainActivity.cs:
public override bool OnOptionsItemSelected(IMenuItem item)
When a user taps a menu item, Android calls the OnOptionsItemSelected method and passes in the menu item that was selected. In this example, the implementation just displays a toast to indicate which menu item was tapped.
Build and run ToolbarFun to see the new menu items in the toolbar. The Toolbar now displays three menu icons as seen in this screenshot:
When a user taps the Edit menu item, a toast is displayed to indicate that the OnOptionsItemSelected method was called:
When a user taps the overflow menu, the Preferences menu item is displayed. Typically, less-common actions should be placed in the overflow menu – this example uses the overflow menu for Preferences because it is not used as often as Edit and Save:
For more information about Android menus, see the Android Developer Menus topic.
Troubleshooting
The following tips can help to debug problems that may occur while replacing the action bar with a toolbar.
Activity Already Has an Action Bar
If the app is not properly configured to use a custom theme as explained in Apply the Custom Theme, the following exception may occur while running the app:
In addition, an error message such as the following may be produced: Java.Lang.IllegalStateException: This Activity already has an action bar supplied by the window decor.
To correct this error, verify that the android:theme attribute for the custom theme is added to (in Properties/AndroidManifest.xml) as described earlier in Apply the Custom Theme. In addition, this error may be caused if the Toolbar layout or custom theme is not configured properly.
Related Links
- Lollipop Toolbar (sample)
- AppCompat Toolbar (sample)
Замена панели действий
Одним из наиболее распространенных вариантов является Toolbar замена панели действий по умолчанию пользовательским Toolbar (при создании нового проекта Android она использует панель действий по умолчанию). Toolbar Так как предоставляет возможность добавлять фирменные логотипы, заголовки, элементы меню, кнопки навигации и даже пользовательские представления в раздел пользовательского интерфейса действия, он предлагает значительное обновление по умолчанию.
Чтобы заменить панель действий по умолчанию приложения на : Toolbar
- Создайте пользовательскую тему и измените свойства приложения таким образом, чтобы он использовал эту новую тему.
- windowActionBar Отключите атрибут в пользовательской теме и включите windowNoTitle атрибут.
- Определение макета Toolbar для .
- Toolbar Включите макет в файл макета Main.axml действия.
- Добавьте код в метод действия OnCreate , чтобы найти Toolbar и вызвать SetActionBar установку в ToolBar качестве панели действий.
В следующих разделах подробно объясняется этот процесс. Создается простое приложение, а его панель действий заменена настраиваемым Toolbar .
Запуск проекта приложения
Создайте проект Android с именем ToolbarFun (дополнительные сведения о создании нового проекта Android см. в разделе Hello, Android ). После создания этого проекта задайте целевые и минимальные уровни API Android для Android 5.0 (уровень API 21 — Lollipop) или более поздней версии. Дополнительные сведения о настройке уровней версий Android см. в разделе «Общие сведения об уровнях API Android». При создании и запуске приложения отображается панель действий по умолчанию, как показано на этом снимке экрана:
Создание пользовательской темы
Откройте каталог resources/values и создайте файл с именем styles.xml. Замените его содержимое следующим XML-кодом:
Этот XML-код определяет новую пользовательскую тему с именем MyTheme , основанную на теме Theme.Material.Light.DarkActionBar в Lollipop. Для windowNoTitle атрибута задано скрытие true строки заголовка:
- true
Чтобы отобразить пользовательскую панель инструментов, значение по умолчанию ActionBar должно быть отключено:
- false
Для цвета фона панели инструментов используется оливково-зеленый colorPrimary параметр:
- #5A8622
Применение пользовательской темы
Измените свойства/AndroidManifest.xml и добавьте следующий android:theme атрибут в элемент, чтобы приложение использовало настраиваемую MyTheme тему:
Дополнительные сведения о применении пользовательской темы к приложению см. в разделе «Использование пользовательских тем».
Определение макета панели инструментов
В каталоге Resources/layout создайте файл с именем toolbar.xml. Замените его содержимое следующим XML-кодом:
Этот XML-код определяет пользователь Toolbar , заменяющий панель действий по умолчанию. Минимальная высота Toolbar заданного значения имеет размер панели действий, которую он заменяет:
android:minHeight="?android:attr/actionBarSize"
Цвет фона Toolbar устанавливается на цвет оливково-зеленого цвета, определенный ранее в styles.xml:
android:background="?android:attr/colorPrimary"
Начиная с Lollipop атрибут android:theme может использоваться для стиля отдельного представления. Темы ThemeOverlay.Material , представленные в Lollipop, позволяют наложить темы по умолчанию Theme.Material , перезаписывать соответствующие атрибуты, чтобы сделать их светлыми или темными. В этом примере используется темная тема, Toolbar чтобы ее содержимое было светло в цвете:
android:theme="@android:style/ThemeOverlay.Material.Dark.ActionBar"
Этот параметр используется для контрастирования элементов меню с темным цветом фона.
Включение макета панели инструментов
Измените файл макета resources/layout/Main.axml и замените его содержимое следующим XML:
Этот макет включает определенный Toolbar в toolbar.xml и используется RelativeLayout для указания того, что Toolbar оно должно быть помещено в самую верхнюю часть пользовательского интерфейса (над кнопкой).
Поиск и активация панели инструментов
Измените MainActivity.cs и добавьте следующую инструкцию using:
using Android.Views;
Кроме того, добавьте в конец OnCreate метода следующие строки кода:
var toolbar = FindViewById(Resource.Id.toolbar); SetActionBar(toolbar); ActionBar.Title = "My Toolbar";
Этот код находит Toolbar и вызывает SetActionBar , чтобы Toolbar принять характеристики панели действий по умолчанию. Заголовок панели инструментов изменен на «Моя панель инструментов«. Как показано в этом примере кода, ToolBar можно напрямую ссылаться на панель действий. Скомпилируйте и запустите это приложение— настраиваемое Toolbar отображается вместо панели действий по умолчанию:
Обратите внимание, что стиль Toolbar не зависит от Theme.Material.Light.DarkActionBar темы, применяемой к остальной части приложения.
Если при запуске приложения возникает исключение, см . раздел «Устранение неполадок » ниже.
Добавление элементов меню
В этом разделе меню добавляются в . Toolbar Верхняя правая область ToolBar меню зарезервирована для элементов меню— каждый пункт меню (также называемый элементом действия) может выполнять действие в текущем действии или выполнять действие от имени всего приложения.
Чтобы добавить меню в Toolbar :
- Добавьте значки меню (при необходимости) в mipmap- папки проекта приложения. Google предоставляет набор бесплатных значков меню на странице значков «Материал».
- Определите содержимое элементов меню, добавив новый файл ресурса меню в разделе «Ресурсы или меню«.
- OnCreateOptionsMenu Реализуйте метод действия. Этот метод увеличивает элементы меню.
- OnOptionsItemSelected Реализуйте метод действия. Этот метод выполняет действие при нажатии элемента меню.
В следующих разделах подробно демонстрируется этот процесс, добавив элементы меню «Изменить » и «Сохранить » в настроенные Toolbar элементы меню.
Значки меню установки
Продолжая использовать ToolbarFun пример приложения, добавьте значки меню в проект приложения. Скачайте значки панели инструментов, распакуйте и скопируйте содержимое извлеченных папок mipmap- в папки mipmap проекта в разделе ToolbarFun/Resources и добавьте каждый добавленный файл значка в проект.
Определение ресурса меню
Создайте подкаталог меню в разделе «Ресурсы«. В подкаталоге меню создайте файл ресурса меню с именем top_menus.xml и замените его содержимое следующим XML:
Этот XML-код создает три пункта меню:
- Элемент меню «Изменить «, использующий ic_action_content_create.png значок (карандаш).
- Элемент меню «Сохранить «, использующий ic_action_content_save.png значок (дискет).
- Элемент меню «Параметры» , не имеющий значка.
Атрибуты элементов меню «Изменить» и «Сохранить» заданы ifRoom . Этот showAsAction параметр приводит к отображению этих элементов меню в Toolbar том случае, если для них достаточно места. Наборы элементов never showAsAction меню «Параметры» — это приводит к отображению меню «Параметры» в меню переполнения (три вертикальные точки).
Реализация OnCreateOptionsMenu
Добавьте следующий метод в MainActivity.cs:
public override bool OnCreateOptionsMenu(IMenu menu)
Android вызывает OnCreateOptionsMenu метод, чтобы приложение может указать ресурс меню для действия. В этом методе ресурс top_menus.xml раздувается в переданный menu . Этот код приводит к отображению новых элементов меню «Изменить», «Сохранить» и «Параметры«. Toolbar
Реализация OnOptionsItemSelected
Добавьте следующий метод в MainActivity.cs:
public override bool OnOptionsItemSelected(IMenuItem item)
Когда пользователь нажимает элемент меню, Android вызывает OnOptionsItemSelected метод и передает выбранный элемент меню. В этом примере реализация просто отображает всплывающее уведомление, указывающее, какой элемент меню был касался.
Создайте и запустите ToolbarFun , чтобы увидеть новые элементы меню на панели инструментов. Теперь Toolbar отображаются три значка меню, как показано на этом снимке экрана:
Когда пользователь нажимает элемент меню «Изменить «, отображается всплывающее уведомление, указывающее, что OnOptionsItemSelected метод был вызван:
Когда пользователь нажимает меню переполнения, отображается элемент меню «Параметры «. Как правило, менее распространенные действия должны размещаться в меню переполнения. В этом примере используется меню переполнения для параметров , так как оно не используется так часто, как изменение и сохранение:
Дополнительные сведения о меню Android см. в разделе меню разработчика Android.
Устранение неполадок
Следующие советы помогут выполнить отладку проблем, которые могут возникнуть при замене панели действий панелью инструментов.
Действие уже имеет панель действий
Если приложение неправильно настроено на использование пользовательской темы, как описано в разделе «Применение пользовательской темы», при запуске приложения может возникнуть следующее исключение:
Кроме того, может быть создано сообщение об ошибке: Java.Lang.IllegalStateException: у этого действия уже есть панель действий, предоставляемая декором окна.
Чтобы исправить эту ошибку, убедитесь, что android:theme атрибут настраиваемой темы добавлен (в свойствах или AndroidManifest.xml), как описано ранее в разделе «Применить настраиваемую тему». Кроме того, эта ошибка может быть вызвана, если Toolbar макет или пользовательская тема настроена неправильно.
Связанные ссылки
- Панель инструментов Lollipop (пример)
- Панель инструментов AppCompat (пример)
Как убрать Action Bar в Xamarin.Forms?
2.2 Создать интерфейс IStatusBar в проекте где лежит MainPage.xaml.cs:
public interface IStatusBar < /// /// Hide /// void HideStatusBar(); /// /// Show /// void ShowStatusBar(); >
2.3 И в проекте Андройд:
[assembly: Dependency(typeof(StatusBarHelper))] public class StatusBarHelper : IStatusBar < private WindowManagerFlags _originalFlags; private bool IsHide < get; set; >#region IStatusBar implementation /// /// Hide /// public void HideStatusBar() < if (IsHide) return; IsHide = true; var activity = (AppCompatActivity)Forms.Context; var attrs = activity.Window.Attributes; _originalFlags = attrs.Flags; attrs.Flags |= WindowManagerFlags.Fullscreen; activity.Window.Attributes = attrs; >/// /// Show /// public void ShowStatusBar() < if (!IsHide) return; IsHide = false; var activity = (AppCompatActivity)Forms.Context; var attrs = activity.Window.Attributes; attrs.Flags = _originalFlags; activity.Window.Attributes = attrs; >#endregion >
Убрать статус бар и отключить кнопку назад
Добрый день!
Если кто знает, подскажите, как можно развернуть приложение на полный экран или просто убрать статус бар.
А так же отключить кнопку назад.
Даже примерно не могу понять в какую сторону копать.
Добавлено через 7 минут
нашел в свойствах проекта объявление манифеста и там EXPAND_STATUS_BAR
но с этим явно надо делать что-то еще
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
Ответы с готовыми решениями:
Убрать статус бар
Добрый день. Как я понимаю есть action bar и status bar. В моем приложении я хочу убрать.
Убрать статус бар
Уберите меню, там где: Файл, Элементы, Действия. Только чтобы после этого работоспособность.
Доступ к статус бар
Доброго времени суток! Я человек новый в программировании под iOS, но возник у меня такой.
Собственный статус-бар
Народ, знает кто как создать собственный статус бар? У меня есть приложение, развернутое на весь.
Регистрация: 03.04.2013
Сообщений: 238
1 2 3 4
protected override bool OnBackButtonPressed() { return true; }
Это касательно второго пункта. С первым пока не сталкивался, как разберешься напиши, может пригодиться)
Регистрация: 27.04.2015
Сообщений: 525
АндрюхаРостовск, не пойму как этот метод использовать.
По по поводу первого вопроса частично решил.
В MainActivity.cs добавить
Window.SetFlags(WindowManagerFlags.Fullscreen, WindowManagerFlags.Fullscreen);
однако есть два момента.
1. При запуске приложения и до первого тапа статус бар проглядывает;
2. При открытии нового окна так же проглядывает полоска показывающая кусок предыдущего окна.
Добавлено через 1 минуту
Хотел приложить скриншоты, но что-то не грузятся
Добавлено через 6 минут
не распространяется на IOS, я его вообще не использую в проекте.
Добавлено через 1 час 13 минут
Вроде решил.
1- Лечится установкой цвета backgrounda (я всюду использую Grid);
2- проблема появляется только у модальных окон, заменил на бычные и стало хорошо.
Возможно оба решения являются костылями.