Android bar on the top

Material Design. Динамический Toolbar на живом примере

Уверен, что те, кто следят за изменениями в мире Android, заметили, что Toolbar начинает играть в приложениях всё более значимую роль. Например в последней версии Gmail клиента в Toolbar вынесен почти весь функционал по работе с почтой, а в новом Google Chrome Toolbar отвечает за работу с текстом страниц.

В данной статье я постараюсь рассказать о создании динамического Toolbar, который позволит пользователю работать с контентом четырьмя различными способами в рамках одного Activity. Мы рассмотрим весь процесс разработки Toolbar-a начиная с xml файлов стилей и заканчивая анимацией иконок, а в конце статьи я оставлю ссылку на GitHub репозиторий с примером полностью рабочего приложения.

Начнём с постановки задачи

Мы будем разрабатывать Toolbar для приложения, которое позволит пользователю следить за изменениями цен на акции. На главном экране будет расположен список всех акций, за которыми следит пользователь, мы также должны реализовать базовый функционал: удаление, поиск и сортировку акций. Вот так я реализовал этот функционал с помощью динамического Toolbar-a:

Стандартный режим Режим поиска Режим удаления Режим сортировки

Создаём xml файлы конфигураций

Итак, в первую очередь нам нужно создать xml файл самого Toolbar-a. Я советую сделать это в отдельном файле, так как в будущем мы скорее всего захотим использовать один и тот же (или похожий) Toolbar во всех Activity нашего приложения.

Теперь мы можем добавить toolbar.xml в xml Activity следующим образом:
res/layout/activity_main.xml

Поскольку в нашем Toolbar будет располагаться виджет поиска, мы можем настроить его внешний в вид в файле styles.xml нашего приложения. В 21 версии Android SDK появилось гораздо больше возможностей для кастомизации виджета поиска (SearchView Widget), вы можете посмотреть полный список атрибутов по этой ссылке: AppCompat v21 — Material Design for Pre-Lollipop Devices! В этом же файле мы зададим цвет нашего Toolbar.

И наконец создадим файл со списком всех элементов нашего Toolbar-а. Тут у нас есть несколько вариантов:

  • В начале создать только те элементы, которые будут видны в стандартном режиме, а затем в коде добавлять или удалять элементы при переходе между режимами.
  • Сразу создать все существующие элементы в xml файле, а в коде просто управлять их видимостью.

Я выбрал второй вариант так как у нас не так много элементов внутри Toolbar и нам нет смысла экономить память храня в ней только видимые элементы.

Также существует два способа создания элементов Toolbar:

    Создавать элементы внутри меню (Menu), как экземпляры класса MenuItem. Этот способ использовался в предыдущих версиях Анрдроид (API Level

Источник

Android bar on the top

Top app bars display information and actions related to the current screen.

Contents

Using top app bars

Before you can use Material top app bars, you need to add a dependency to the Material Components for Android library. For more information, go to the Getting started page.

Читайте также:  Deer hunter 2014 android

Making top app bars accessible

Android’s top app bar component APIs provide support for the navigation icon, action items, overflow menu and more, to inform the user what each action performs. While optional, their use is strongly encouraged.

When using icons for navigation, action items and other elements of top app bars, you should set a content description for them so that screen readers like TalkBack are able to announce their purpose or action.

For an overall content description of the top app bar, set an android:contentDescription or use the setContentDescription method on the MaterialToolbar .

For the navigation icon, this can be achieved via the app:navigationContentDescription attribute or setNavigationContentDescription method.

For action items and items within the overflow menu, the content description needs to be set in the menu:

For images within collapsing top app bars, set an android:contentDescription or use the setContentDescription method for the ImageView .

There are four types of top app bars: 1. Center aligned, 2. Small, 3. Medium, 4. Large.

For implementation purposes, the Center aligned & Small types can be grouped into Regular top app bars, while the Medium & Large types can be grouped into Collapsing top app bars.

Top app bars use the following APIs and source code:

Regular top app bars

The top app bar provides content and actions related to the current screen. It’s used for branding, screen titles, navigation, and actions.

Small top app bar example

The following example shows a Small top app bar with a page title, a navigation icon, two actions, and an overflow menu.

In menu/navigation icon drawables:

Note: The above example is the recommended approach and, in order for it to work, you need to use a Theme.Material3.* theme containing the NoActionBar segment, such as the Theme.Material3.Light.NoActionBar . If not, an action bar will be added to the current Activity window. The MaterialToolbar can be set as the support action bar and thus receive various Activity callbacks, as shown in this guide.

Applying scrolling behavior to the top app bar

The following example shows the top app bar positioned at the same elevation as content. Upon scroll, it increases elevation and lets content scroll behind it.

The following example shows the top app bar disappearing upon scrolling up, and appearing upon scrolling down.

Center aligned top app bar example

All of the same guidance and code from the sections above is relevant for Center aligned top app bars. The only additional configuration needed for centering is setting the app:titleCentered and/or app:subtitleCentered attributes to true on your MaterialToolbar .

Читайте также:  Настройка wifi через инженерное меню андроид

Anatomy and Key properties

  1. Container
  2. Navigation icon (optional)
  3. Title (optional)
  4. Action menu items (optional)
Element Attribute Related method(s) Default value
Color android:background setBackground
getBackground
?attr/colorSurface
MaterialToolbar elevation android:elevation setElevation
getElevation
4dp
AppBarLayout elevation android:stateListAnimator setStateListAnimator
getStateListAnimator
0dp to 4dp (see all states)

Navigation icon attributes

Element Attribute Related method(s) Default value
MaterialToolbar icon app:navigationIcon setNavigationIcon
getNavigationIcon
null
MaterialToolbar icon color app:navigationIconTint setNavigationIconTint ?attr/colorOnSurface
Element Attribute Related method(s) Default value
MaterialToolbar title text app:title setTitle
getTitle
null
MaterialToolbar subtitle text app:subtitle setSubtitle
getSubtitle
null
MaterialToolbar title color app:titleTextColor setTitleTextColor ?attr/colorOnSurface
MaterialToolbar subtitle color app:subtitleTextColor setSubtitleTextColor ?attr/colorOnSurfaceVariant
MaterialToolbar title typography app:titleTextAppearance setTitleTextAppearance ?attr/textAppearanceTitleLarge
MaterialToolbar subtitle typography app:subtitleTextAppearance setSubtitleTextAppearance ?attr/textAppearanceTitleMedium
MaterialToolbar title centering app:titleCentered setTitleCentered false
MaterialToolbar subtitle centering app:subtitleCentered setSubtitleCentered false
CollapsingToolbarLayout collapsed title typography app:collapsedTitleTextAppearance setCollapsedTitleTextAppearance ?attr/textAppearanceTitleLarge
CollapsingToolbarLayout expanded title typography app:expandedTitleTextAppearance setExpandedTitleTextAppearance ?attr/textAppearanceHeadlineSmall for Medium
?attr/textAppearanceHeadlineMedium for Large
CollapsingToolbarLayout collapsed title color android:textColor (in app:collapsedTitleTextAppearance ) or app:collapsedTitleTextColor setCollapsedTitleTextColor ?attr/colorOnSurface
CollapsingToolbarLayout expanded title color android:textColor (in app:expandedTitleTextAppearance ) or app:expandedTitleTextColor setExpandedTitleTextColor ?attr/colorOnSurface
CollapsingToolbarLayout expanded title margins app:expandedTitleMargin* setExpandedTitleMargin* 16dp
CollapsingToolbarLayout title max lines app:maxLines setMaxLines
getMaxLines
1

Action items attributes

Element Attribute Related method(s) Default value
MaterialToolbar menu app:menu inflateMenu
getMenu
null
MaterialToolbar icon color N/A N/A ?attr/colorOnSurfaceVariant

Overflow menu attributes

Element Attribute Related method(s) Default value
MaterialToolbar icon android:src and app:srcCompat in actionOverflowButtonStyle (in app theme) setOverflowIcon
getOverflowIcon
@drawable/abc_ic_menu_overflow_material (before API 23) or @drawable/ic_menu_moreoverflow_material (after API 23)
MaterialToolbar overflow theme app:popupTheme setPopupTheme
getPopupTheme
@style/ThemeOverlay.Material3.*
MaterialToolbar overflow item typography textAppearanceSmallPopupMenu and textAppearanceLargePopupMenu in app:popupTheme or app theme N/A ?attr/textAppearanceBodyLarge

Scrolling behavior attributes

Element Attribute Related method(s) Default value
MaterialToolbar or CollapsingToolbarLayout scroll flags app:layout_scrollFlags setScrollFlags
getScrollFlags
(on AppBarLayout.LayoutParams )
noScroll
MaterialToolbar collapse mode app:collapseMode setCollapseMode
getCollapseMode
(on CollapsingToolbar )
none
CollapsingToolbarLayout content scrim color app:contentScrim setContentScrim
setContentScrimColor
setContentScrimResource
getContentScrim
null
CollapsingToolbarLayout status bar scrim color app:statusBarScrim setStatusBarScrim
setStatusBarScrimColor
setStatusBarScrimResource
getStatusBarScrim
@empty
CollapsingToolbarLayout scrim animation duration app:scrimAnimationDuration setScrimAnimationDuration
getScrimAnimationDuration
600
CollapsingToolbarLayout collapsing animation interpolator app:titlePositionInterpolator setTitlePositionInterpolator @null
AppBarLayout lift on scroll app:liftOnScroll setLiftOnScroll
isLiftOnScroll
true
Element Style
Surface background color style Widget.Material3.AppBarLayout

Default style theme attribute: ?attr/appBarLayoutStyle

Element Style
Default style Widget.Material3.Toolbar
Surface background color style Widget.Material3.Toolbar.Surface
On Surface color style Widget.Material3.Toolbar.OnSurface

Default style theme attribute: ?attr/toolbarStyle

Additional style theme attributes: ?attr/toolbarSurfaceStyle

Element Style
Default style Widget.Material3.CollapsingToolbar
Medium style Widget.Material3.CollapsingToolbar.Medium
Large style Widget.Material3.CollapsingToolbar.Large

Default style theme attribute: ?attr/collapsingToolbarLayoutStyle

Additional style theme attributes: ?attr/collapsingToolbarLayoutMediumStyle , ?attr/collapsingToolbarLayoutLargeStyle

See the full list of styles and attrs.

Collapsing top app bars

The larger collapsing top app bars can be used for longer titles, to house imagery, or to provide a stronger presence to the top app bar.

Medium top app bar example

The following example shows a Medium collapsing top app bar with a page title, a navigation icon, an action icon, and an overflow menu.

Large top app bar example

The following example shows a Large collapsing top app bar with a page title, a navigation icon, an action icon, and an overflow menu.

Adding an image to a collapsing top app bar

A collapsing top app bar with an image background, a page title, a navigation icon, two action icons, and an overflow menu:

Applying scrolling behavior to a collapsing top app bar

When scrolling up, the collapsing top app bar transforms into a regular top app bar.

Contextual action bar

Contextual action bars provide actions for selected items. A top app bar can transform into a contextual action bar, remaining active until an action is taken or it is dismissed.

Contextual action bar example

API and source code:

The following example shows a contextual action bar with a contextual title, a close icon, two contextual action icons, and an overflow menu:

In menu/navigation icons:

Anatomy and Key properties

  1. Close button (instead of a navigation icon)
  2. Contextual title
  3. Contextual actions
  4. Overflow menu (optional)
  5. Container (not shown)

Close button attributes

Element Attribute Related method(s) Default value
Icon app:actionModeCloseDrawable (in app theme) N/A @drawable/abc_ic_ab_back_material
Color N/A N/A ?attr/colorControlNormal (as Drawable tint)

Contextual title attributes

Element Attribute Related method(s) Default value
Title text N/A setTitle
getTitle
null
Subtitle text N/A setSubtitle
getSubtitle
null
Title typography app:titleTextStyle N/A @style/TextAppearance.Material3.ActionBar.Title
Subtitle typography app:subtitleTextStyle N/A @style/TextAppearance.Material3.ActionBar.Subtitle

Contextual actions attributes

Element Attribute Related method(s) Default value
Menu N/A menuInflater.inflate in ActionMode.Callback null
Icon color N/A N/A ?attr/colorControlNormal (as Drawable tint)

Overflow menu attributes

Element Attribute Related method(s) Default value
Icon android:src and app:srcCompat in actionOverflowButtonStyle (in app theme) setOverflowIcon
getOverflowIcon
@drawable/abc_ic_menu_overflow_material (before API 23) or @drawable/ic_menu_moreoverflow_material (after API 23)
Overflow item typography textAppearanceSmallPopupMenu and textAppearanceLargePopupMenu in app theme N/A ?attr/textAppearanceTitleMedium
Element Attribute Related method(s) Default value
Color app:background N/A ?attr/actionModeBackground
Height app:height N/A ?attr/actionBarSize
Overlay window app:windowActionModeOverlay (in app theme) N/A false
Element Style
Default style Widget.Material3.ActionMode

Default style theme attribute: actionModeStyle

Theming the top app bar

The top app bar supports Material Theming and can customize color, typography and shape.

Top app bar theming example

API and source code:

A regular top app bar with Material Theming:

Implementing top app bar theming

Use theme attributes in res/values/styles.xml , which applies to all top app bars and affects other components:

Use default style theme attributes, styles and theme overlays, which applies to all top app bars but does not affect other components:

Use the style in the layout, which affects only this top app bar:

Источник

Читайте также:  Инструмент разработчика для андроид
Оцените статью