18 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Пример работы с BottomNavigationView. Нижнее меню в Android

Lost In Android Support Material Design Library: Bottom Navigation

This article is the second part of the series, Lost in Android Support Material Design Library. If you didn’t read the previous one you can start from here.

Hey, Android Developer. I would like to tell you something about Android Bottom Navigation View. The Bottom Navigation View is a part of the Google Android Material Design Library. It creates a bottom navigation bar, making it easier to explore switch between with a single tap.

Let’s start with Bottom Navigation View

To begin we need to update our build.gradle file.

Next, we simply need to add the BottomNavigationView widget to our desired layout file like below:

You’ll notice that we have a app:menu attribute property set to it. When implementing a BottomNavigationView the way to show icons and text is through app:menu .

Creating app:menu to display text and Icon

In the last part of the previous section, we’ve talked about app:menu . The item shows inside the Bottom Navigation View are added by inflating the menu file. For example, you could have a bottom_navigation_menu.xml file inside the res->menu directory.

Every item inside the menu tag should contain at minimum of three attributes.

  • android: id A unique resource id for the menu item.
  • android: title The menu title as a string resource or raw string.
  • android: icon An image to used as the menu item icon. The image must be a drawable resource.

For more information about the menu, item properties check out this link.

So far if you run the application you’ll get the following result:

You can also add menu items to your Bottom Navigation View programmatically:

Add a listener for menu items click Events

So we’ve successfully implemented our menu. Now we need to detect when navigation items have interacted.

On clicking the menu item we simply showing toast on screen accordingly.

Applying a material style to Bottom Navigation View

The Material Design (MD) library provides several considerable styling options. But after the recent update 1.1.0-alpha06, we can now show BadgeDrawable over the item icon in the top right corner. We’ll see how to add BadgeDrawbale at the end of this article. Now let’s look at all possible styling options.

Читать еще:  Файловая система флешки RAW

Change look of text and icon

At the most basic level, what if we need to change the icon and text color of menu items. I’m pretty sure most of us want to override the default styling behavior of Bottom Navigation View. The easiest way to do it by adding the itemIconTint and itemTextColor property attribute inside the com.google.*******.BottomNavigationView xml tag.

With such basic styling, you can expect your Bottom Navigation View look like this:

The above demo looks fine but there’s not state showing for which item is enabled or which is disabled. Mostly, the disabled states show a different color than the enabled one. With that the way we need to create a new drawable file inside the res-> drawable directory for enabled/disabled state.

For example, we could have a bottom_navigation_item_colors.xml file that contains:

Next, update the itemIconTint property attribute.

Finally, run the application to view the progress so far.

Color ripple Effects

The color of navigation item touch ripple can be customized with itemRippleColor attribute.

After the above change, we’ll see the light red color ripple effect when the user presses the menu items.

Text Labeling

The labelVisibilityMode attribute can be used to show the text labels on each navigation item. Now if you look at the above examples of Bottom Navigation you’ll notice that the label only shows when the item is selected. Well, that is because, if we did not set any labelVisibilityMode the default label auto will be used. There are four types of labelVisibilityMode added inside the Android Material Design library for Bottom Navigation View.

  1. labeled: Will keep all labels visible.
  2. unlabeled: Label will be hidden for all navigation items.
  3. auto(default): It used an item count to determine whether to show or hide the label. If the navigation item count is 3 the mode will behave as labeled, 4 or more the behavior will be selected.
  4. selected: Will only show the label for the selected item.
Читать еще:  Проверьте подключены ли все сетевые кабели?

When to use which labelVisibilityMode

From the Material Design here are a couple of guidelines when to use which labelVisibilityMode .

  • 3 items: Use labeled visibility mode to show icons and text for all navigation items.
  • 4-5 items: Use selected visibility mode to display icon and text on the selected navigation item. Inactive items only show icons.

Working with BadgeDrawable (Notification Badge)

The Bottom Navigation View items can include badges in their right upper corner as a notification. The badges contain dynamic information such as a number of pending requests and a colorful dot. Without further ado let’s create a badge notification on navigation item.

Show notification Badge

The showBadge method returns an instance of BadgeDrawable. Visually what we’ll find is after adding the badge notification to clock menu item is below.

You see there a slight red dot icon appearing at the right side of the clock menu icon. A badge displayed without a number is the default behavior. Now let’s say I want to show a notification count 1, for the clock menu item. The BadgeDrawable class exposes the convenience method to add notification count via the setNumber method.

With the above change in code, you’ll get the following result.

Remove notification Badge

Notification must be removed or dismissed once we tap on the item. We can do this by the setOnNavigationItemSelectedListener method to detect whether the item showing badge notification then simply removed it.

More Resources

Hurrah. Thus, we have successfully implemented and demonstrated the use of Android Bottom Navigation View. If you have any questions, suggestions and want any help you can add comments at the end of this article. If you like the post don’t forget to hit the below ♥️ button.

Читать еще:  Microsoft патентует клавиатуру с жестовым управлением

Thank you for being and here and keep reading…

Реализация BottomAppBar. Часть 2: Меню и элемент управления Navigation Drawer

В предыдущей статье мы обсудили основы BottomAppBar, который не так давно представили на Google I/O 2018 как часть Material компонентов для Android. Мы рассмотрели способ реализации BottomAppBar и изучили его атрибуты. Также BottomAppBar может отображать элементы меню и элемент управления Navigation Drawer, которые раньше мы использовали в тулбаре.

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

Меню BottomAppBar

Сначала необходимо создать .xml файл в каталоге res/menu для элементов меню, которые должны быть показаны в BottomAppBar. Вот мой файл bottomappbar_menu.xml:

В MainActivity, в которой вы вызываете setSupportActionBar(bottom_app_bar), добавьте следующий код в метод:

Теперь элементы меню должны отображаться в BottomAppBar.

Обработка кликов по элементам меню

Для обработки кликов по элементам меню необходимо добавить следующий код в MainActivity:

Теперь меню в BottomAppBar настроено и должно функционировать правильно:

Элемент управления Navigation Drawer в BottomAppBar

Обычно Navigation Drawer реализуется при помощи NavigationView, расположенного в левой части приложения. С BottomAppBar поведение Navigation Drawer изменилось. Теперь Navigation Drawer представляет собой модальное окно в нижней части приложения.

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

Файл меню для Navigation Drawer также должен быть расположен в res/menu.

Затем нужно создать класс, расширяющий BottomSheetDialogFragment, который и будет создавать модальное окно:

Следующие строки кода нужно добавить в метод onOptionsItemSelected, который используется для обработки кликов по элементам меню. При клике по значку навигации будет создаваться экземпляр объекта BottomNavigationDrawerFragment и отображаться Navigation View.

Вот код макета MainActivity:

А для кликов по элементам в окне Navigation Drawer вы можете использовать следующий код внутри класса BottomNavigationDrawerFragment:

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

голоса
Рейтинг статьи
Ссылка на основную публикацию
Статьи c упоминанием слов: