Bottom navigation library android

Содержание
  1. Урок 17. Android Navigation. Знакомство с BottomNavigationView. Как добавить фрагменты в панель Bottom Navigation.
  2. Создаем проект
  3. Неоходимые библиотеки
  4. Граф навигации
  5. Добавление экранов
  6. Хост навигации
  7. BottomNavigationView
  8. Добавление пунктов меню
  9. Добаление идентификаторов в контроллер навигации
  10. Рефакторинг
  11. Kotlin Android BottomNavigationView Examples
  12. What You Will Learn
  13. What is a Bottom Navigation Bar?
  14. Video Tutorial
  15. Bottom Navigation Example in Java
  16. Step 1: Create Activity
  17. Step 2: Create Layout Resource
  18. Step 3: Create Menu Resource file
  19. Example 1: Kotlin Android Simple BottomNavigationView with Fragments Example
  20. Step 1: Dependencies
  21. Step 2: Design Layouts
  22. Step 3: Create Fragments
  23. Step 4: Create Activity
  24. Reference
  25. Example 2 – BottomNavigationView with Fragments
  26. Step 1: Create Favorites Fragment
  27. Step 2: Create a Video Fragment
  28. Step 3: Create a Music Fragment
  29. Step 4: Create Main Activity
  30. Download
  31. Example 3 – BottomNavigationview with Shimmer Effect
  32. Download Code
  33. Credit
  34. Example 4 – BottomNavigationView with Swipeable fragments
  35. Download Code
  36. Best Android Bottom Navigation Libraries 2021
  37. (a). BottomNavigation
  38. (b). BottomNavigationViewEx
  39. (c). Material-BottomNavigation
  40. Step 1: Install it
  41. Step 2: Create Menu
  42. Step 3: Add to Layout
  43. Step 4: Write Code
  44. Adding Badges
  45. Reference
  46. Other Bottom Navigation Libraries
  47. (a). BottomBar (Deprecated)
  48. Step 1: Install it
  49. Step 2: Create menu
  50. Step 3: Add to Layout
  51. Step 4: Write Code
  52. Reference
  53. Oclemy

Урок 17. Android Navigation. Знакомство с BottomNavigationView. Как добавить фрагменты в панель Bottom Navigation.

На прошлом уроке мы работали с анимацией переходов между экранами. На этом уроке познакомимся с нижней панелью навигации BottomNavigationView, которая позволяет переходить между экранами – пунктами назначения навигации, а также наглядно информирует пользователя о том, на каком экране он находится. Разберемся, как добавить Bottom Navigation в андроид приложение и как добавить в BottomNavigationView новые фрагменты.

Создаем проект

С одной стороны, создать простое приложение с панелью навигации можно, не написав ни одной строчки кода. Достаточно воспользоваться готовым макетом Bottom Navigation Activity на этапе создания проекта в Android Studio. При этом создается проект приложения с нижней панелью навигации BottomNavigationView на главном экране, в которой отображается три пункта. При нажатии каждого из них меняются экраны приложения. Это все хорошо, скажете вы, но если нужно добавить или убрать экраны и пункты для них? Или добавить нижнюю навигацию в существующее приложение?

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

Неоходимые библиотеки

Если открыть файл сборки build.gradle, в секции dependencies можно увидеть подключенные библиотеки из пакета androidx.navigation (с ktx для проектов на kotlin) которые нам уже знакомы по предыдущим урокам на тему навигации в приложении. Если вы добавляете нижнюю навигацию в существующее приложение, то начинать нужно с добавления этих библиотек в ваш проект.

Граф навигации

В папке res есть папка navigation, в которой размещен все тот же граф навигации, его вы помните по предыдущим урокам. Без него, как вы понимаете, не обходится здесь и нижняя панель навигации.

Добавление экранов

Нажмите кнопку New Destination вверху и выберите Create New Destination. На экране добавления фрагментов выберите шаблон Fragment (with ViewModel). Добавьте один за другим два фрагмента – четвертый и пятый экран. Я их так и назову: FourthFragment и FifthFragment.

Вы можете выбрать при добавлении просто Fragment blank. Но связка Fragment + ViewModel предоставляет преимущества сохранения состояния экрана при изменении конфигурации – например, при повороте устройства. Подробнее об этом мы говорили в Уроке 6.

В граф навигации добавилось два фрагмента. Переименуйте их идентификаторы в соответствии с именами других пунктов назначения: navigation_fourth и navigation_fifth. Переименование всегда лучше делать через рефакторинг, нажатием комбинации Shift + F6 – это гарантирует изменение всех возможных связей.

Можно было оставить идентификаторы как было, но более правильно с точки зрения Code Convention, чтобы названия однотипных элементов были логически похожими. Да и находить их будет легче потом.

Также измените значение параметра android:label — оно используется для заголовка экрана. Впишите сюда текст, который вы хотите видеть в заголовке соответствующего экрана, желательно сохранить его затем в строковых ресурсах. Для сохранения нажмите желтую лампочку и выберите пункт «Extract string resourse», а затем придумайте название строки, которая сохранится в файле res/values/strings.xml.

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

Хост навигации

Если мы откроем папку layout, то увидим макеты всех фрагментов – пунктов назначения, и макет главного активити.

Макет activity_main.xml содержит компонент fragment – это хост навигации, в котором отображаются фрагменты – пункты назначения. Он связан с графом навигации через параметр app:navGraph.

Читайте также:  Айклауд вход с андроида облако

BottomNavigationView

Также здесь присутствует и компонент BottomNavigationView. Это и есть нижняя панель навигации. Компонент BottomNavigationView является частью библиотеки компонентов материального дизайна. Эта библиотека должна быть импортирована в файле сборки модуля:

Обычно она уже есть в проекте по умолчанию.

Рассмотрим компонент BottomNavigationView боле подробно. Он содержит идентификатор nav_view, и имеет значение ширины – 0dp. Это рекомендуемое значение для всех элементов, ширина которых регулируется ограничениями, заданными корневым элементом разметки ConstraintLayout. Мы видим эти ограничения ниже, они привязывают панель к нижней части родителя, который, в свою очередь, занимает весь экран.

Высота BottomNavigationView задана по контенту, но можно установить фиксированную нужного вам размера.

Далее идут два параметра layout_marginStart и layout_marginEnd. Они регламентируют отступ слева и справа, но поскольку значения здесь равны нулю, они ни на что не влияют, и их можно удалить.

Параметр android:background содержит ссылку на атрибут windowBackground и делает фон панели такой же, как фон экрана. Если вы хотите получить цвет панели, такой как на гайдлайнах сайта material.io, то замените параметр android:background=»?android:attr/windowBackground» таким:

Кстати, на сайте material.io можно найти много полезных рекомендаций как по дизайну, так и по реализации компонентов визуального интерфейса. На странице Bottom Navigation, например, указано, что рекомендованное число элементов панели нижней навигации должно быть от трех до пяти. Подписи должны быть максимально короткими и состоять, по возможности, из одного слова.

На вкладе implementation дается пример реализации нижней панели без графа навигации, а также примеры кастомизации и оформления фона и цвета пунктов нижней панели, добавления пунктам бейджей и т.д.

Добавление пунктов меню

Но вернемся к нашему проекту и компоненту BottomNavigationView в макете activity_main.xml.

Нас интересует последний параметр:

Он ссылается на файл bottom_nav_menu.xml в папке res/menu. Этот файл содержит описание пунктов меню нижней панели навигации. Следовательно, добавлять новые пункты следует здесь.

Добавим пару элементов для четвертого и пятого фрагментов. Их идентификаторы должны совпадать с идентификаторами пунктов назначения в графе навигации. Также укажите соответствующие строковые ресурсы в качестве названия пунктов в android:title.

Добаление идентификаторов в контроллер навигации

Осталось добавить идентификаторы пунктов навигации в конфигурацию контроллера навигации в классе MainActivity.

Переменная класса АppBarConfiguration содержит набор идентификаторов пунктов навигации и передается вместе с контроллером – хостом навигации – в функцию setupActionBarWithNavController. Это нужно для того, чтобы система считала каждый из пунктов назначения пунктом верхнего уровня. В противном случае каждый фрагмент будет отображать стрелку возврата назад в тулбаре слева, как это отображается на дочерних активити и фрагментах.

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

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

Рефакторинг

Теперь можно навести порядок в проекте. Дело в том, что изначально в проекте фрагменты каждого экрана со своими ViewModel расположены в отдельных папках по имени каждого пункта меню нижней панели навигации, и все это лежит в папке ui. Новые же добавленные фрагменты попали просто в главный пакет. Нужно создать в папке ui новые пакеты по имени добавленных экранов. Затем нужно перенести туда добавленные фрагменты вместе с их привязанными ViewModel. Делается это простым перетаскиванием в дереве проекта, с открытием окна рефакторинга, в котором нужно подтвердить операцию.
Теперь вы знаете, как добавить Bottom Navigation в приложение.

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

Источник

Kotlin Android BottomNavigationView Examples

Welcome to today’s tutorial. In this piece we want to look at some options for inducing a bottom bar in your application. Mostly we will be looking at how to work with the botttom navigation bar component.

What You Will Learn

Here are the concepts you will learn in this tutorial:

  1. What is a Bottom Navigation bar
  2. How to use a bottom navigation view – simple example.
  3. How to create swipeable bottom bar.
  4. How to use BottomNavigationView with Fragments and Viewpager.
  5. How to create animated bottomnavigationview with shimmer effect.

What is a Bottom Navigation Bar?

It represents a standard bottom navigation bar for application. It is an implementation of material design bottom navigation.

Bottom navigation bars make it easy for users to explore and switch between top-level views in a single tap. They should be used when an application has three to five top-level destinations.

The bar can disappear on scroll, based on HideBottomViewOnScrollBehavior , when it is placed within a CoordinatorLayout and one of the children within the CoordinatorLayout is scrolled. This behavior is only set if the layout_behavior property is set to HideBottomViewOnScrollBehavior.

Читайте также:  Где хранится переписка whatsapp андроид

The bar contents can be populated by specifying a menu resource file. Each menu item title, icon and enabled state will be used for displaying bottom navigation bar items. Menu items can also be used for programmatically selecting which destination is currently active. It can be done using MenuItem#setChecked(true) .

Here are the steps followed in using a bottom navigation view:

Add it to your Layout Resource as follows:

Create Navigation Items menu resource file as follows:

Then lastly reference and use it in your java/kotlin code. Proceed to check our examples.

Video Tutorial

If you prefer a video tutorial then we have one:

We start by seeing what BottomNavigation is as a general design pattern, then see the BottomNavigationView for android, then look at some examples.

Bottom Navigation Example in Java

Step 1: Create Activity

MainActivity.java

Here is our main activity file. This is the only java we write in this example.

Step 2: Create Layout Resource

activity_main.xml

Here’s our main activity’s layout.

Step 3: Create Menu Resource file

bottom_navigation_main.xml

This is our menu. Place it under the menu resource directory.

Let’s look at some more downloadable bottomnavigationview examples.

Example 1: Kotlin Android Simple BottomNavigationView with Fragments Example

This is a simple bottom navigationview example written in Kotlin. In this example you will be able to switch through 3 fragments by clicking the corresponding bottom navigation ba item.

The fragments simply contain a textview with some text. Check the demo below:

Step 1: Dependencies

No special or third party dependency is needed.

Step 2: Design Layouts

There will be 4 layouts:

  1. 3 Fragment layouts
  2. 1 main activity layout.

Fragment Layouts

The general design of the fragment layouts is similar. All have a textview at the center that will display the text fro te chosen fragment:

MainActivity Layout

On the other hand the main activity layout will contain a framelayout as well as the bottomnavigationview:

Step 3: Create Fragments

There will be 3 fragments:

(a). fra1.kt

The first fragment:

(b). frag2.kt

The code for the second fragment:

(c). frag3.kt

The code for the third fragment:

Step 4: Create Activity

Finally you need to create an activity that will host the fragments. The major thing here is that you will have a function that will be setting a fragment to the activity via fragment transaction as follows;

So you willb basically be invoking this method and passing in the appropriate fragment based on the bottom navigation view item selected:

Here is the full code;

MainActivity.kt

Reference

Find the code reference links below:

No. Link
1. Download code
2. Browse code
3. Follow code author

Example 2 – BottomNavigationView with Fragments

In this lesson we want to explore BottomNavigationView examples. We want to look at as many examples as we can. Be aware that some examples may be using older support libraries, however you can easily update the code to androidx using android studio.

This example is written in Java. It teaches how to show bottom navigation with icons and connect each tab with Fragments.

When a tab is selected, its corresponding fragment is rendered as well.

Step 1: Create Favorites Fragment

(a). FavoritesFragmemt

Create a Favorites Fragment:

Step 2: Create a Video Fragment

(b). VideoFragmemt

The Videos Fragment:

Step 3: Create a Music Fragment

(c). MusicFragmemt

The Music Fragment:

Step 4: Create Main Activity

(d). MainActivity

The activity that will host all these fragments:

If you run the project you will get the following:

Download

Example 3 – BottomNavigationview with Shimmer Effect

The difference with the first example is shown in the below image:

It only works if you set white color for background android:background=»@android:color/white»

Note that ripple effect will disappear if you use app:itemBackground property.

Handling enabled/disabled state:

You need to create selector file:

If you want change standard grey ripple effect, change colorControlHighlight property in AppTheme so it looks like following:

Use 26% alpha for colored ripples.

MainActivity

Here is the code:

Download Code

Credit

This code has been shared by @Luksha

Example 4 – BottomNavigationView with Swipeable fragments

This example improves on the other examples by adding the ability to swipe from one fragment to the other. This swipe capability is added via ViewPager.

(a). FirstFragment

The FirstFragment code:

(b). SecondFragment

The SecondFragment code:

(c). ThirdFragment

The ThirdFragment code:

(d). OnPageChangeAdapter

The OnPageChangeAdapter code:

(e). MainActivity

The MainActivity code:

Download Code

Download code below:

No. Link
1. Download code
2. Follow Project Author

Best Android Bottom Navigation Libraries 2021

A Bottom navigation bar is a navigation component that allows movement between primary destinations in an app. They typically display three to five destinations at the bottom of a screen. Each destination is represented by an icon and an optional text label. When a bottom navigation icon is tapped, the user is taken to the top-level navigation destination associated with that icon.

According to material Bottom Navigation guidelines the following are the principals of bottom navigation:

  1. Ergonomic – The bottom navigation bar should be easy to reach on a handheld mobile device.
  2. Consistent – The bottom navigation bar should appear at the bottom of every screen.
  3. Related – Bottom navigation bar destinations should be of equal importance.

In this blog post we explore some of the best android bottom navigation libraries. I have used some of these libraries in my projects and I plan to use some of them. These libraries are listed randomly on a first discovered, first listed manner.

(a). BottomNavigation

This Library helps users to use Bottom Navigation Bar (A new pattern from google) with ease and allows ton of customizations.

Here is a gif demo of this library in use:

Here are the features of this library:

  • This library is very customizale. You can attest to that by looking at the gif demo above.
  • It adheres to Google’s bottom navigation bar guidelines.
  • It allows you to select your own background and tab mode.
  • You can assign each tab a seperate color
  • You can render badges in the tabs. The badges can be customized.

Installation

Install the library using the following statement:

How to use

First add the following in your xml layout:

Then in your code, add bottom navigation items:

And listen to tab selection events:

Read more here. Find full example here. Follow the author here.

(b). BottomNavigationViewEx

An enhancement of BottomNavigationView.

This library supports API 9 and above.

This library supports many styles.

You can use this library with ViewPager:

It also supports badges:

This library also supports centering a floating action button on the bottom navigation bar:

Installation

To install this library your compile sdk version must be 25 and above:

Go to your root level build.gradle and add the following:

Then add your implementation statement in the app level build.gradle:

How to use it

To use this library, first go to your xml layout and add the following:

Then in your java/kotlin code reference the view:

If you want to disable animation:

If you want to change text and icon size:

To connect this bottom navigation view with viewpager:

If you want to use a badge, then first install the badgeview:

NB/= Other usages with this library are the same as the official BottomNavigationView.

Read more here. Find full example here. Follow the author here.

(c). Material-BottomNavigation

Bottom Navigation widget component inspired by the Google Material Design Guidelines at Design Specs.

Here is the demo:

Step 1: Install it

To use it you start by installing it:

Step 2: Create Menu

Next create a menu resource file to contain bottomnavigation items:

Step 3: Add to Layout

The next step is to add the bottomnavigation to your xml layout:

Step 4: Write Code

next you can simply reference the bottomnavigation view in your code and use it.

Adding Badges

We can also add badges in bottomnavigation items as follows:

Here’s the code to do it:

To remove the badge use the following code:

Reference

Here are the links:

No. Link
1. Read more
2. Examples

Other Bottom Navigation Libraries

(a). BottomBar (Deprecated)

A custom view component that mimics the new Material Design Bottom Navigation pattern.

Here is the demo of bottombar:

Step 1: Install it

You start by installing it as below:

Step 2: Create menu

You then create the menu resource file:

Step 3: Add to Layout

Next you add it to your XML layout:

Step 4: Write Code

Then you write code, for example listen to selection events of the bottombar items:

Reference

Here are the links:

No. Link
1. Read more
2. Examples

report this ad

Oclemy

Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .

Источник

Читайте также:  Андроид подписки где найти
Оцените статью