Androidx appcompat widget toolbar что это

от admin

Androidx appcompat widget toolbar что это

Статья проплачена кошками — всемирно известными производителями котят.

Если статья вам понравилась, то можете поддержать проект.

Toolbar

Компонент появился в Android 5 Lollipop, но доступен и для старых устройств в рамках Material Design. Можно найти в разделе Containers на панели инструментов.

Toolbar является дальнейшим развитием ActionBar, но имеет больше возможностей. Он гораздо гибче в настройках. Теперь вы можете задать многие свойства через XML, также вы можете задать различную высоту и вставлять в него другие компоненты. Кроме того, Toolbar может играть не только роль заголовка в приложении, его можно разместить и в других местах.

У вас должна быть прописана зависимость (скорее всего уже есть):

Важный момент — Toolbar замещает ActionBar, поэтому следует позаботиться, чтобы они не работали одновременно. Самое простое — выбрать тему без использования ActionBar, например, <style name="Theme.Dolphin_Kot" parent="Theme.MaterialComponents.DayNight.NoActionBar"> или более ранний вариант <style name="AppTheme" parent = "Theme.AppCompat.NoActionBar">.

Помните, что сам по себе компонент Toolbar может служить не только заменой ActionBar, но и как отдельная панель снизу, слева, справа, быть плавающей поверх экрана, иметь различную ширину и высоту.

Создадим разметку с использованием Toolbar:

Запускаем и видим две цветные полоски Toolbar, а между ними приютился TextView.

Я пока не видел практического применения Toolbar на экране активности в виде отдельной дополнительной панели, поэтому сосредоточимся на первой панели, которая должна служить заменой ActionBar. На данный момент панель совсем не похожа на заголовок приложения — нет ни значка, ни текста, ни меню. Просто пустая полоска.

Чтобы подсказать приложению, что панель является заменой ActionBar, нужно присоединить её в коде через метод setSupportActionBar().

Теперь мы видим привычный заголовок приложения. Панель стала частью заголовка. Сейчас в заголовке выводится имя приложения. Если вы уберёте комментарий со строки setTitle(), то увидите, что этот метод активности действует и на Toolbar — ещё одно доказательство, что панель встроилась в активность и стала её родной частью. Если вы добавите код для меню, то в панели появятся также и три вертикальные точки.

Toolbar

Добавим различные настройки для него, они вам знакомы по ActionBar:

Это только часть методов. В документации найдёте остальное. Метод Toolbar.setTitle() у меня не заработал, в заголовке всё равно выводился текст из ресурсов app_name. Но работает метод активности setTitle().

Toolbar

Upd. Насколько я понял, в методе onCreate() рано вызывать метод Toolbar.setTitle(), так как текст заголовка переписывается текстом из манифеста (android:labed). Нужно сделать это чуть позже. Как вариант, вызвать в методе onPostCreate(), который сработает после onCreate(). Если действовать через щелчок кнопки, то текст меняется без проблем.

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

Toolbar

Если вы используете дизайн Material, то для фона желательно использовать соответствующие цвета, например, так.

В качестве темы используйте следующий вариант.

Обратите внимание, что используется пространство имён xmlns:app=»http://schemas.android.com/apk/res-auto».

Сам по себе Toolbar автоматически не цепляет тему активности, поэтому при необходимости нужно дублировать нужные свойства.

В старых проектах родительский элемент часто использовал отступы и ваша панель может быть уже. Просто уберите их.

Стилизация

Соберём все стили вместе.

Ещё один стиль добавляет пустое место сверху (добавить в MyToolbar). Редко используется.

Применим через style, tittleTextAppearance and subtittleTextAppearance:

Прозрачность достигается через windowTranslucentStatus:

Добавляем кнопки действий на Toolbar

Чтобы на панели появились три вертикальные точки для вызова меню, нужно просто добавить соответствующие методы. Но также можно вывести на панель и кнопки действия, минуя эти точки.

Добавим кнопку действия на Toolbar. Так как в нашем случае Toolbar служит заменой ActionBar, то наш код ничем не будет отличаться от старого способа для панели действий. Просто освежим память.

В файле res/menu/menu_main.xml добавим новый пункт (при необходимости создайте папку и файл вручную).

Для демонстрации я использовал системные ресурсы для изображения и готовый текст. В своих проектах вы должны использовать правильные способы использования строковых и графических ресурсов. Если убрать первый пункт, то три точки не появятся, а будет только наша кнопка действия.

Menu

Созданная кнопка будет использоваться для перехода на вторую активность. Создайте её самостоятельно.

Перейдём в класс основной активности и добавим код для перехода на вторую активность.

Используем <include>

Во многих примерах часто используют приём включения одного файла разметки в другой.

Создадим файл action_toolbar.xml в папке res/layout и укажем в качестве корневого элемента Toolbar.

Toolbar

Переходим в разметку основной активности и добавим созданную панель через тег include.

Конечно, мы могли бы добавить и напрямую тег Toolbar в разметку активности, но такой способ удобнее, если приложение будет состоять из нескольких активностей и в каждой из них должна быть наша панель.

Если вставлять код в шаблон с RelativeLayout, то текст «Hello World» может наложиться на панель. Поэтому укажем ему место под панелью.

Напишем код. Объявим переменную типа Toolbar и присоединим её к экрану активности.

Запустим код и получим прозрачную панель.

Toolbar

Вряд ли мы ожидали такого варианта. Добавим фон.

Смотрим на результат. Видим, что панель имеет отступы, которые были добавлены в шаблоне.

Toolbar

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

Теперь мы получили правильную панель.

Toolbar

Интересно отметить, что на старом устройстве можно вызвать меню из двух мест. Современный способ через три точки на панели.

Toolbar

Старый способ через аппаратную кнопку меню. Меню будет вызвано из другого места.

Toolbar

Можно изменить цвет меню, добавив дополнительный атрибут.

Toolbar

Можно задать свою отдельную тему для панели, определив цвет текста, который должен быть достаточно контрастным на фоне панели. Добавим в файл styles.xml

Подключим стили к панели.

Я намеренно задал разные цвета для атрибутов android:textColorPrimary и android:textColorSecondary, чтобы было заметно, где они используются.

Toolbar

Теперь видно, что первый атрибут отвечает за текст на панели, а второй за точки, которые вызывают меню.

Для Toolbar также можно указать следующие атрибуты:

Системный размер высоты для панели приложения можно использовать и в стандартном атрибуте высоты:

Если хотите использовать стандартную тему для панели, не переопределяя никаких атрибутов, то так и пишите:

Если мы хотим использовать Toolbar не как замену ActionBar, а как отдельную панель, то её создание и присоединение к ней меню может быть следующим.

При использовании SearchView на панели также были внесены изменения. Можно задать стили для данного компонента. Не проверял, оставлю на память.

При использовании на панели меню и других компонентов с выпадающими элементами может понадобиться следующий код.

В API 21 также появились новые стили для элементов меню.

Применим к панели.

Style Toolbar

Вложенный Toolbar

Toolbar можно вложить в какой-нибудь контейнер, например, CardView. Сам на практике не использовал. Но для общего развития оставлю.

Добавим пару ресурсов в файл dimens.xml:

Создадим разметку экрана.

В макете у первой панели установлена большая высота, а CardView частично налезает на главную панель. И при этом содержит вторую панель.

Также обратите внимание на компонент View с высотой 1dp оранжевого цвета, который добавляет полоску под панелью. Вы можете усложнить пример, добавив тень и другие эффекты.

Добавим на вторую панель кнопку действия. Для этого создадим ресурс меню res/menu/menu_main.xml:

Код для активности.

Вложенный Toolbar

Значок возврата

Если вторая активность зависит от первой, то в манифесте прописывают атрибут parentActivityName.

В этом случае на панель у второй активности можно добавить специальный значок возврата обратно в родительскую активность в виде стрелки.

Вам не придётся писать код для возврата на родительскую активность, система сама сделает возврат по щелчку на значке.

NavigationIcon

Цвет значка определяется системой. Можно программно изменить его. Поменяем цвет стрелки на красный.

Если вы хотите заменить системный значок стрелки на что-то своё, то добавьте стиль в MyToolbar (см. выше):

Можно переопределить поведение значка возврата. Не хотите возвращаться на родительскую активность? Напишите свой код.

Androidx appcompat widget toolbar что это

In Android applications, Toolbar is a kind of ViewGroup that can be placed in the XML layouts of an activity. It was introduced by the Google Android team during the release of Android Lollipop(API 21). The Toolbar is basically the advanced successor of the ActionBar. It is much more flexible and customizable in terms of appearance and functionality. Unlike ActionBar, its position is not hardcoded i.e., not at the top of an activity. Developers can place it anywhere in the activity according to the need just like any other View in android. Toolbar use material design theme features of Android and thus it provides backward compatibility up to API 7(Android 2.1). One can use the Toolbar in the following two ways:

  1. Use as an ActionBar: In an app, the toolbar can be used as an ActionBar in order to provide more customization and a better appearance. All the features of ActionBar such as menu inflation, ActionBarDrawerToogle, etc. are also supported in Toolbar.
  2. Use a standalone Toolbar: It can be used to implement a certain kind of design to an application that can not be fulfilled by an ActionBar. For example, showing a Toolbar at a position other than the top of the activity or showing multiple Toolbars in an activity.

Features supported by the Toolbar are much more focused and customizable than the ActionBar. Following are the components that can be added to make a user-appealing Toolbar:

  • Navigation button: This element is aligned vertically with respect to the minimum height of the Toolbar. It is used as a guide for switching between other destinations within an app. The appearance of this element can be in many forms such as navigation menu toggle, close, collapse, done, a simple up arrow, or any other kind of glyph required by the app.
  • Brand logo/App icon: It is one of the most important aspects of an application as it provides a kind of identity. The height of the logo/icon is generally up to the height of the Toolbar but it can be extended as per the need.
  • Title and Subtitle: The purpose of providing a title to the Toolbar is to give information regarding the current position within the navigation hierarchy of an app. The Subtitle is used to indicate any kind of extended information about the content.
  • ActionMenuView: It is similar to the Action Buttons in ActionBar that display some important actions/elements of the app which may be required to the users frequently. Elements of this menu are placed to the end(rightmost side) of the Toolbar.
  • Multiple Custom Views: Android allows developers to add one or more Views such as ImageView, TextView, etc. within the layout of the Toolbar. These views are treated as children of the Toolbar layout and their position can be adjusted according to the need.

Designing a Toolbar

Working with Toolbar is very similar to any operate a View. One can easily assign constraints, change height and width, choose a background color, and much more. To carry out these same tasks in ActionBar, extra lines of code is needed to be written. Here is an example to use the Toolbar as an ActionBar. Following is the step by step method which covers the complete procedure.

Note: Following steps are performed on Android Studio version 4.0

Toolbar

A standard toolbar for use within application content.

A Toolbar is a generalization of action bars for use within application layouts. While an action bar is traditionally part of an opaque window decor controlled by the framework, a Toolbar may be placed at any arbitrary level of nesting within a view hierarchy. An application may choose to designate a Toolbar as the action bar for an Activity using the setSupportActionBar() method.

  • A navigation button. This may be an Up arrow, navigation menu toggle, close, collapse, done or another glyph of the app’s choosing. This button should always be used to access other navigational destinations within the container of the Toolbar and its signified content or otherwise leave the current context signified by the Toolbar. The navigation button is vertically aligned within the Toolbar’s minimum height, if set.
  • A branded logo image. This may extend to the height of the bar and can be arbitrarily wide.
  • A title and subtitle. The title should be a signpost for the Toolbar’s current position in the navigation hierarchy and the content contained there. The subtitle, if present should indicate any extended information about the current content. If an app uses a logo image it should strongly consider omitting a title and subtitle.
  • One or more custom views. The application may add arbitrary child views to the Toolbar. They will appear at this position within the layout. If a child view’s Toolbar.LayoutParams indicates a value of the view will attempt to center within the available space remaining in the Toolbar after all other elements have been measured.
  • An action menu. The menu of actions will pin to the end of the Toolbar offering a few frequent, important or typical actions along with an optional overflow menu for additional actions. Action buttons are vertically aligned within the Toolbar’s minimum height, if set.

In modern Android UIs developers should lean more on a visually distinct color scheme for toolbars than on their application icon. The use of application icon plus title as a standard layout is discouraged on API 21 devices and newer.

Summary

Constructors
public Toolbar(Context context)

Collapse a currently expanded action view.

Dismiss all currently showing popup menus, including overflow or submenus.

Retrieve the currently configured content description for the collapse button view.

Return the current drawable used as the collapse icon.

Gets the ending content inset for this toolbar.

Gets the end content inset to use when action buttons are present.

Gets the left content inset for this toolbar.

Gets the right content inset for this toolbar.

Gets the starting content inset for this toolbar.

Gets the start content inset to use when a navigation button is present.

Gets the content inset that will be used on the ending side of the bar in the current toolbar configuration.

Gets the content inset that will be used on the left side of the bar in the current toolbar configuration.

Gets the content inset that will be used on the right side of the bar in the current toolbar configuration.

Gets the content inset that will be used on the starting side of the bar in the current toolbar configuration.

Return the current logo drawable.

Return the description of the toolbar’s logo.

Return the Menu shown in the toolbar.

Retrieve the currently configured content description for the navigation button view.

Return the current drawable used as the navigation icon.

Return the current drawable used as the overflow icon.

Return the subtitle of this toolbar.

Returns the title of this toolbar.

Check whether this Toolbar is currently hosting an expanded action view.

Hide the overflow items from the associated menu.

Inflate a menu resource into this toolbar.

Only the items in the that were provided by MenuProviders should be removed and repopulated, leaving all manually inflated menu items untouched, as they should continue to be managed manually.

Check whether the overflow menu is currently showing.

Set a content description for the collapse button if one is present.

Set a content description for the collapse button if one is present.

Set the icon to use for the toolbar’s collapse button.

Set the icon to use for the toolbar’s collapse button.

Force the toolbar to collapse to zero-height during measurement if it could be considered «empty» (no visible elements with nonzero measured size)

Sets the start content inset to use when action buttons are present.

Sets the content insets for this toolbar.

Sets the content insets for this toolbar relative to layout direction.

Sets the start content inset to use when a navigation button is present.

Set a logo drawable.

Set a logo drawable from a resource id.

Set a description of the toolbar’s logo.

Set a description of the toolbar’s logo.

Must be called before the menu is accessed

Set a content description for the navigation button if one is present.

Set a content description for the navigation button if one is present.

Set the icon to use for the toolbar’s navigation button.

Set the icon to use for the toolbar’s navigation button.

Set a listener to respond to navigation events.

Set a listener to respond to menu item click events.

Set the icon to use for the overflow button.

Specifies the theme to use when inflating popup menus.

Set the subtitle of this toolbar.

Set the subtitle of this toolbar.

Sets the text color, size, style, hint color, and highlight color from the specified TextAppearance resource.

Sets the text color of the subtitle, if present.

Sets the text color of the subtitle, if present.

Set the title of this toolbar.

Set the title of this toolbar.

Sets the title margin.

Sets the bottom title margin in pixels.

Sets the ending title margin in pixels.

Sets the starting title margin in pixels.

Sets the top title margin in pixels.

Sets the text color, size, style, hint color, and highlight color from the specified TextAppearance resource.

Sets the text color of the title, if present.

Sets the text color of the title, if present.

Show the overflow items from the associated menu.

Constructors

Methods

Specifies the theme to use when inflating popup menus. By default, uses the same theme as the toolbar itself.

Parameters:

resId: theme used to inflate popup menus

Returns:

resource identifier of the theme used to inflate popup menus, or 0 if menus are inflated against the toolbar theme

Sets the title margin.

Parameters:

start: the starting title margin in pixels
top: the top title margin in pixels
end: the ending title margin in pixels
bottom: the bottom title margin in pixels

Returns:

the starting title margin in pixels

See also:

Sets the starting title margin in pixels.

Parameters:

margin: the starting title margin in pixels

See also:

Returns:

the top title margin in pixels

See also:

Sets the top title margin in pixels.

Parameters:

margin: the top title margin in pixels

See also:

Returns:

the ending title margin in pixels

See also:

Sets the ending title margin in pixels.

Parameters:

margin: the ending title margin in pixels

See also:

Returns:

the bottom title margin in pixels

See also:

Sets the bottom title margin in pixels.

Parameters:

margin: the bottom title margin in pixels

See also:

Set a logo drawable from a resource id.

This drawable should generally take the place of title text. The logo cannot be clicked. Apps using a logo should also supply a description using Toolbar.setLogoDescription(int).

Parameters:

resId: ID of a drawable resource

Check whether the overflow menu is currently showing. This may not reflect a pending show operation in progress.

Returns:

true if the overflow menu is currently showing

Show the overflow items from the associated menu.

Returns:

true if the menu was able to be shown, false otherwise

Hide the overflow items from the associated menu.

Returns:

true if the menu was able to be hidden, false otherwise

Dismiss all currently showing popup menus, including overflow or submenus.

Set a logo drawable.

This drawable should generally take the place of title text. The logo cannot be clicked. Apps using a logo should also supply a description using Toolbar.setLogoDescription(int).

Parameters:

drawable: Drawable to use as a logo

Return the current logo drawable.

Returns:

The current logo drawable

Set a description of the toolbar’s logo.

This description will be used for accessibility or other similar descriptions of the UI.

Parameters:

resId: String resource id

Set a description of the toolbar’s logo.

This description will be used for accessibility or other similar descriptions of the UI.

Parameters:

description: Description to set

Return the description of the toolbar’s logo.

Returns:

A description of the logo

Check whether this Toolbar is currently hosting an expanded action view.

An action view may be expanded either directly from the MenuItem it belongs to or by user action. If the Toolbar has an expanded action view it can be collapsed using the Toolbar.collapseActionView() method.

Returns:

true if the Toolbar has an expanded action view

Collapse a currently expanded action view. If this Toolbar does not have an expanded action view this method has no effect.

An action view may be expanded either directly from the MenuItem it belongs to or by user action.

Returns the title of this toolbar.

Returns:

The current title.

Set the title of this toolbar.

A title should be used as the anchor for a section of content. It should describe or name the content being viewed.

Parameters:

resId: Resource ID of a string to set as the title

Set the title of this toolbar.

A title should be used as the anchor for a section of content. It should describe or name the content being viewed.

Parameters:

title: Title to set

Return the subtitle of this toolbar.

Returns:

The current subtitle

Set the subtitle of this toolbar.

Subtitles should express extended information about the current content.

Parameters:

resId: String resource ID

Set the subtitle of this toolbar.

Subtitles should express extended information about the current content.

Parameters:

subtitle: Subtitle to set

Sets the text color, size, style, hint color, and highlight color from the specified TextAppearance resource.

Sets the text color, size, style, hint color, and highlight color from the specified TextAppearance resource.

Sets the text color of the title, if present.

Parameters:

color: The new text color in 0xAARRGGBB format

Sets the text color of the title, if present.

Parameters:

color: The new text color

Sets the text color of the subtitle, if present.

Parameters:

color: The new text color in 0xAARRGGBB format

Sets the text color of the subtitle, if present.

Parameters:

color: The new text color

Retrieve the currently configured content description for the navigation button view. This will be used to describe the navigation action to users through mechanisms such as screen readers or tooltips.

Returns:

The navigation button’s content description

Set a content description for the navigation button if one is present. The content description will be read via screen readers or other accessibility systems to explain the action of the navigation button.

Parameters:

resId: Resource ID of a content description string to set, or 0 to clear the description

Set a content description for the navigation button if one is present. The content description will be read via screen readers or other accessibility systems to explain the action of the navigation button.

Parameters:

description: Content description to set, or null to clear the content description

Set the icon to use for the toolbar’s navigation button.

The navigation button appears at the start of the toolbar if present. Setting an icon will make the navigation button visible.

If you use a navigation icon you should also set a description for its action using Toolbar.setNavigationContentDescription(int). This is used for accessibility and tooltips.

Parameters:

resId: Resource ID of a drawable to set

Set the icon to use for the toolbar’s navigation button.

The navigation button appears at the start of the toolbar if present. Setting an icon will make the navigation button visible.

If you use a navigation icon you should also set a description for its action using Toolbar.setNavigationContentDescription(int). This is used for accessibility and tooltips.

Parameters:

icon: Drawable to set, may be null to clear the icon

Return the current drawable used as the navigation icon.

Returns:

The navigation icon drawable

Set a listener to respond to navigation events.

This listener will be called whenever the user clicks the navigation button at the start of the toolbar. An icon must be set for the navigation button to appear.

Parameters:

listener: Listener to set

See also: Toolbar

Retrieve the currently configured content description for the collapse button view. This will be used to describe the collapse action to users through mechanisms such as screen readers or tooltips.

Returns:

The collapse button’s content description

Set a content description for the collapse button if one is present. The content description will be read via screen readers or other accessibility systems to explain the action of the collapse button.

Parameters:

resId: Resource ID of a content description string to set, or 0 to clear the description

Set a content description for the collapse button if one is present. The content description will be read via screen readers or other accessibility systems to explain the action of the navigation button.

Parameters:

description: Content description to set, or null to clear the content description

Return the current drawable used as the collapse icon.

Returns:

The collapse icon drawable

Set the icon to use for the toolbar’s collapse button.

The collapse button appears at the start of the toolbar when an action view is present .

Parameters:

resId: Resource ID of a drawable to set

Set the icon to use for the toolbar’s collapse button.

The collapse button appears at the start of the toolbar when an action view is present .

Parameters:

icon: Drawable to set, may be null to use the default icon

Return the Menu shown in the toolbar.

Applications that wish to populate the toolbar’s menu can do so from here. To use an XML menu resource, use Toolbar.inflateMenu(int).

Returns:

The toolbar’s Menu

Set the icon to use for the overflow button.

Parameters:

icon: Drawable to set, may be null to clear the icon

Return the current drawable used as the overflow icon.

Returns:

The overflow icon drawable

Inflate a menu resource into this toolbar.

Inflate an XML menu resource into this toolbar. Existing items in the menu will not be modified or removed.

Parameters:

resId: ID of a menu resource to inflate

Set a listener to respond to menu item click events.

This listener will be invoked whenever a user selects a menu item from the action buttons presented at the end of the toolbar or the associated overflow.

Parameters:

listener: Listener to set

Sets the content insets for this toolbar relative to layout direction.

The content inset affects the valid area for Toolbar content other than the navigation button and menu. Insets define the minimum margin for these components and can be used to effectively align Toolbar content along well-known gridlines.

Parameters:

contentInsetStart: Content inset for the toolbar starting edge
contentInsetEnd: Content inset for the toolbar ending edge

Gets the starting content inset for this toolbar.

The content inset affects the valid area for Toolbar content other than the navigation button and menu. Insets define the minimum margin for these components and can be used to effectively align Toolbar content along well-known gridlines.

Returns:

The starting content inset for this toolbar

Gets the ending content inset for this toolbar.

The content inset affects the valid area for Toolbar content other than the navigation button and menu. Insets define the minimum margin for these components and can be used to effectively align Toolbar content along well-known gridlines.

Returns:

The ending content inset for this toolbar

Sets the content insets for this toolbar.

The content inset affects the valid area for Toolbar content other than the navigation button and menu. Insets define the minimum margin for these components and can be used to effectively align Toolbar content along well-known gridlines.

Parameters:

contentInsetLeft: Content inset for the toolbar’s left edge
contentInsetRight: Content inset for the toolbar’s right edge

Gets the left content inset for this toolbar.

The content inset affects the valid area for Toolbar content other than the navigation button and menu. Insets define the minimum margin for these components and can be used to effectively align Toolbar content along well-known gridlines.

Returns:

The left content inset for this toolbar

Gets the right content inset for this toolbar.

The content inset affects the valid area for Toolbar content other than the navigation button and menu. Insets define the minimum margin for these components and can be used to effectively align Toolbar content along well-known gridlines.

Returns:

The right content inset for this toolbar

Gets the start content inset to use when a navigation button is present.

Different content insets are often called for when additional buttons are present in the toolbar, as well as at different toolbar sizes. The larger value of Toolbar.getContentInsetStart() and this value will be used during layout.

Returns:

the start content inset used when a navigation icon has been set in pixels

See also:

Sets the start content inset to use when a navigation button is present.

Different content insets are often called for when additional buttons are present in the toolbar, as well as at different toolbar sizes. The larger value of Toolbar.getContentInsetStart() and this value will be used during layout.

Parameters:

insetStartWithNavigation: the inset to use when a navigation icon has been set in pixels

See also:

Gets the end content inset to use when action buttons are present.

Different content insets are often called for when additional buttons are present in the toolbar, as well as at different toolbar sizes. The larger value of Toolbar.getContentInsetEnd() and this value will be used during layout.

Returns:

the end content inset used when a menu has been set in pixels

See also:

Sets the start content inset to use when action buttons are present.

Different content insets are often called for when additional buttons are present in the toolbar, as well as at different toolbar sizes. The larger value of Toolbar.getContentInsetEnd() and this value will be used during layout.

Parameters:

insetEndWithActions: the inset to use when a menu has been set in pixels

See also:

Gets the content inset that will be used on the starting side of the bar in the current toolbar configuration.

Returns:

the current content inset start in pixels

Gets the content inset that will be used on the ending side of the bar in the current toolbar configuration.

Returns:

the current content inset end in pixels

Gets the content inset that will be used on the left side of the bar in the current toolbar configuration.

Returns:

the current content inset left in pixels

Gets the content inset that will be used on the right side of the bar in the current toolbar configuration.

Returns:

the current content inset right in pixels

Force the toolbar to collapse to zero-height during measurement if it could be considered «empty» (no visible elements with nonzero measured size)

Must be called before the menu is accessed

Only the items in the that were provided by MenuProviders should be removed and repopulated, leaving all manually inflated menu items untouched, as they should continue to be managed manually.

Using the App Toolbar

Toolbar was introduced in Android Lollipop, API 21 release and is the spiritual successor of the ActionBar. It’s a ViewGroup that can be placed anywhere in your XML layouts. Toolbar’s appearance and behavior can be more easily customized than the ActionBar.

Toolbar works well with apps targeted to API 21 and above. However, Android has updated the AppCompat support libraries so the Toolbar can be used on lower Android OS devices as well. In AppCompat, Toolbar is implemented in the androidx.appcompat.widget.Toolbar class.ura

There are two ways to use Toolbar:

  1. Use a Toolbar as an Action Bar when you want to use the existing ActionBar facilities (such as menu inflation and selection, ActionBarDrawerToggle , and so on) but want to have more control over its appearance.
  2. Use a standalone Toolbar when you want to use the pattern in your app for situations that an Action Bar would not support; for example, showing multiple toolbars on the screen, spanning only part of the width, and so on.

Toolbar vs ActionBar

The Toolbar is a generalization of the ActionBar system. The key differences that distinguish the Toolbar from the ActionBar include:

  • Toolbar is a View included in a layout like any other View
  • As a regular View , the toolbar is easier to position, animate and control
  • Multiple distinct Toolbar elements can be defined within a single activity

Keep in mind that you can also configure any Toolbar as an Activity’s ActionBar, meaning that your standard options menu actions will be display within.

Note that the ActionBar continues to work and if all you need is a static bar at the top that can host icons and a back button, then you can safely continue to use ActionBar .

Using Toolbar as ActionBar

To use Toolbar as an ActionBar, first ensure the AndroidX support library is added to your application build.gradle (Module:app) file:

Second, let’s disable the theme-provided ActionBar. The easiest way is to have your theme extend from Theme.AppCompat.NoActionBar (or the light variant) within the res/values/styles.xml file:

Now you need to add a Toolbar to your Activity layout file. One of the biggest advantages of using the Toolbar widget is that you can place the view anywhere within your layout. Below we place the toolbar at the top of a LinearLayout like the standard ActionBar:

Note: You’ll want to add android:fitsSystemWindows=»true» (learn more) to the parent layout of the Toolbar to ensure that the height of the activity is calculated correctly.

As Toolbar is just a ViewGroup and can be styled and positioned like any other view. Note that this means if you are in a RelativeLayout , you need to ensure that all other views are positioned below the toolbar explicitly. The toolbar is not given any special treatment as a view.

Next, in your Activity or Fragment, set the Toolbar to act as the ActionBar by calling the setSupportActionBar(Toolbar) method:

Note: When using the support library, make sure that you are importing android.support.v7.widget.Toolbar and not android.widget.Toolbar .

Next, we need to make sure we have the action items listed within a menu resource file such as res/menu/menu_main.xml which is inflated above in onCreateOptionsMenu :

For more details about action items in the Toolbar including how to setup click handling, refer to our ActionBar guide. The above code results in the toolbar fully replacing the ActionBar at the top:

From this point on, all menu items are displayed in your Toolbar, populated via the standard options menu callbacks.

Reusing the Toolbar

In many apps, the same toolbar can be used across multiple activities or in alternative layout resources for the same activity. In order to easily reuse the toolbar, we can leverage the layout include tag as follows. First, define your toolbar in a layout file in res/layout/toolbar_main.xml :

Next, we can use the <include /> tag to load the toolbar into our activity layout XML:

and then access the Toolbar by the include id instead:

This allows us to create a consistent navigation experience across activities or configuration changes.

Styling the Toolbar

The Toolbar can be customized in many ways leveraging various style properties including android:theme , app:titleTextAppearance , app:popupTheme . Each of these can be mapped to a style. Start with:

Now, we need to create the custom styles in res/values/styles.xml with:

This results in:

Displaying an App Icon

In certain situations, we might want to display an app icon within the Toolbar . This can be done by adding this code into the Activity

Next, we need to remove the left inset margin that pushes the icon over too far to the left by adding app:contentInsetStart to the Toolbar :

With that the icon should properly display within the Toolbar as expected.

Custom Title View

A Toolbar is just a decorated ViewGroup and as a result, the title contained within can be completely customized by embedding a view within the Toolbar such as:

This means that you can style the TextView like any other. You can access the TextView inside your activity with:

Note that you must hide the default title using setDisplayShowTitleEnabled . This results in:

Translucent Status Bar

In certain cases, the status bar should be translucent such as:

To achieve this, first set these properties in your res/values/styles.xml within the main theme:

The activity or root layout that will have a transparent status bar needs have the fitsSystemWindows property set in the layout XML:

You should be all set. Refer to this stackoverflow post for more details.

Transparent Status Bar

If you want the status bar to be entirely transparent for KitKat and above, the easiest approach is to:

and then add this style to your res/values/styles.xml within the main theme:

You should be all set. Refer to this stackoverflow post for more details.

Reacting to Scroll

We can configure the Toolbar to react and change as the page scrolls:

For example, we can have the toolbar hide when the user scrolls down on a list or expand as the user scrolls to the header. There are many effects that can be configured by using the CoordinatorLayout. First, we need to make sure we add the jetpack libraries to our app/build.gradle file:

Next, inside the activity layout XML such as res/layout/activity_main.xml , we need to setup our coordinated layout with a Toolbar and a scrolling container such as a RecyclerView :

Of course, the RecyclerView could also be replaced with a FrameLayout which could then allow for fragments to be loaded instead:

This type of layout results in the following:

Refer to the guide on CoordinatorLayout and AppBarLayout for additional explanation and specifics. For troubleshooting, refer to this troubleshooting guide.

Advanced Scrolling Behavior for Toolbar

The proper way of reacting to simple scroll behavior is leveraging the CoordinatorLayout built into the Design Support Library as shown in the previous section. However, there are a few other relevant resources around reacting to scrolling events with a more manual approach:

  • Hiding or Showing Toolbar on Scroll — Great guide on an alternate strategy not requiring the CoordinatorLayout to replicate the behavior of the «Google Play Music» app. Sample code can be found here.
  • Hiding or Showing Toolbar using CoordinatorLayout — Great guide that outlines how to use CoordinatorLayout to hide the Toolbar and the FAB when the user scrolls.

With these methods, your app can replicate any scrolling behaviors seen in common apps with varying levels of difficulty not captured with the method shown above.

Читать:
Как из xbox one сделать компьютер

Похожие статьи