Hide bottom navigation android

Содержание
  1. Реализация BottomAppBar. Часть 3: Поведения для Android
  2. Поведение
  3. Макет
  4. Скроллирование
  5. Возвышение
  6. Как динамически скрыть пункт меню в BottomNavigationView?
  7. 9 ответов
  8. Ultimate Guide to Bottom Navigation on Android
  9. In this tutorial, learn to add a Bottom Bar and manage Fragments with it.
  10. What is Bottom Navigation?
  11. When to use?
  12. A simpler way to look at it…
  13. Getting Started
  14. aurelhubert/ahbottomnavigation
  15. ahbottomnavigation — A library to reproduce the behavior of the Bottom Navigation guidelines from Material Design.
  16. Bottom Navigation View with Android Design Support Library
  17. Bottom Bar (BottomNavigationView) was officially added in Design Support v25. It was first introduced in Android via the Material Design guidelines…
  18. Adding Bottom Navigation to Layout
  19. Moving onto Java
  20. 1. Create your Items
  21. 2. Add Bottom Navigation items
  22. 3. Set Listener
  23. Styling Bottom Navigation
  24. Simple Theming
  25. Color Ripple Effects
  26. Text Labels
  27. The Material Design guidelines aren’t always right
  28. Translucent Bottom Navigation
  29. Behaviors
  30. Quick Return Animation
  31. Translucent Navigation with Quick Return
  32. Notification Badge
  33. Show notification
  34. Removing the Notification Icon
  35. Managing Bottom Navigation with Fragments
  36. Maintaining Fragments with ViewPager
  37. Difference between FragmentPagerAdapter and FragmentStatePagerAdapter
  38. FragmentPagerAdapter stores the whole fragment in memory, and could increase a memory overhead if a large amount of…
  39. Creating the ViewPager Adapter
  40. Disable swiping on ViewPager
  41. Connecting ViewPager with PagerAdapter
  42. Handling Click Events
  43. Output
  44. Where to, from here?
  45. Suleiman19/Bottom-Navigation-Demo
  46. Bottom-Navigation-Demo — Implementation of Bottom Navigation with Fragments, using https://github.com/aurelhubert…
  47. Other Options
  48. Wrap Up

Реализация BottomAppBar. Часть 3: Поведения для Android

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

В первой и второй частях нашей серии статей про BottomAppBar мы познакомились с BottomAppBar и обсудили его атрибуты. Также мы объяснили, как реализовать Navigation Drawer и меню приложения в рамках BottomAppBar.

Поведение

Согласно Material Design, компоненты приложения не являются статичными. Они могут перемещаться или трансформироваться, т.е. иметь какое-то поведение. Material Design также формирует некие рамки для такого поведения. В этой статье мы обсудим детали реализации рекомендуемого поведения для BottomAppBar, которое представлено на странице гайдлайнов для BottomAppBar.

Макет

Первый гайдлайн описывает макет BottomAppBar. Вот что предлагается:

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

Основываясь на этом гайдлайне, на главных экранах рекомендуется использовать макет BottomAppBar, показывающий несколько пунктов в меню и центрированную FAB (Floating Action Button). На второстепенных экранах, переход на которые осуществляется с главных, макет BottomAppBar должен состоять из выровненной по правому краю FAB и нескольких дополнительных пунктов в меню. Переходы между этими двумя экранами должны выполняться надлежащим образом. Gif сверху демонстрирует этот гайдлайн.

Теперь давайте посмотрим, как можно реализовать это поведение. У нас есть два xml-файла в папке res/menu для меню каждого экрана:

Когда происходит переход между экранами, например, по нажатию кнопки TOGGLE SCREEN в нашем случае, макет BottomAppBar, включая меню и FAB, должен измениться. Вот базовый код для такого поведения макета BottomAppBar:

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

Скроллирование

Скроллирование — важный триггер поведения для таких компонентов, как BottomAppBar. На странице гайдлайнов Material Design рекомендуется следующее поведение для этого случая:

При скроллировании BottomAppBar может появиться или исчезнуть:
— Скроллирование вниз скрывает BottomAppBar. Если на нём была FAB, она отсоединяется от панели и остается на экране.
— Скроллирование вверх показывает BottomAppBar и снова присоединяет его к FAB, если она там была.

Ниже приведена демонстрация поведения BottomAppBar при скроллировании.

Чтобы использовать это поведение, BottomAppBar и FAB должны быть прямыми дочерними элементами CoordinatorLayout. Затем мы включаем hideOnScroll и устанавливаем флаги скроллирования для BottomAppBar:

Этого вполне достаточно для реализации такого поведения BottomAppBar.

Возвышение

У каждого компонента в мире Material Design есть возвышение, аналогичное нашему физическому миру. У BottomAppBar возвышение — 8dp, а само содержимое экрана возвышается на 0dp. FAB в статичном состоянии возвышается на 12dp. Два компонента, которые мы ещё вспомним в этой статье, Navigation Drawer и Snackbar, возвышаются на 16dp и 6dp соответственно.

Как правило, Snackbar — это компонент для уведомления пользователя, выскакивающий из нижней части экрана. Но если на экране есть BottomAppBar или Navigation Drawer, поведение Snackbar должно измениться. В этих случаях Snackbar следует показывать над нижними компонентами. Вот демонстрация и соответствующий код для реализации:

Как мы уже упоминали, Navigation Drawer возвышается на 16dp, что означает — согласно гайдлайну —

Меню, выпадающие из BottomAppBar (например, Navigation Drawer), открываются как модальные окна на уровень выше, чем сам BottomAppBar.

Ниже приведена реализация нашего Navigation Drawer:

Navigation Drawer является модальным окном и поэтому следует приведённому выше правилу реализации.

Детали реализации этого поведения выглядят следующим образом. В папке res/menu должен быть создан xml-файл меню для Navigation View, который будет использован в Navigation Drawer:

Затем должен быть создан файл макета для фрагмента, использующего Navigation Drawer:

Этот файл макета содержит Navigation View и другие компоненты, формирующие макет для Navigation Drawer. Чтобы создать этот макет, нам нужен класс фрагмента, расширяющий BottomSheetDialogFragment:

При клике по значку Navigation Drawer создаётся экземпляр этого фрагмента, который показывается в виде модального окна:

Это статья завершает нашу серию статей про BottomAppBar. Найти исходный код этой статьи вы можете на Github. Комментируйте и задавайте вопросы.

Источник

Как динамически скрыть пункт меню в BottomNavigationView?

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

9 ответов

removeItem делает свое дело. Не уверен, почему метод setVisible не работает.

Я попробовал большинство решений, но это сработало для меня,

Для динамического сокрытия предмета: bottomNavigationView.findViewById(R.id.xyz).setVisibility(View.GONE);

Для того, чтобы сделать предмет видимым: bottomNavigationView.findViewById(R.id.xyz).setVisibility(View.VISIBLE);

Читайте также:  Как убрать команды нет андроид

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

Мы объявляем массив идентификаторов для рисования и массив идентификаторов заголовков в соответствии с тем, что мы объявили в XML-файле меню. Если true, мы перебираем пункты меню и устанавливаем для их значка, заголовка и их состояния значения по умолчанию. Если значение равно false, мы устанавливаем значок на прозрачный значок (удаление значка влияет на его размер), задаем для заголовка панели инструментов пустую строку и отключаем ее.

Меню BottomNavigationView:

Пустой значок (ic_empty.xml):

Пустой заголовок (title_empty):

У меня в kotlin это работает так:

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

RemoveItem смещает элементы меню на панели, когда элемент (ы) скрыт. Я нашел немного лучший способ. Создайте группу пунктов меню, которые вы хотели бы скрыть в своем меню xml.

В вашем bottom_menu.xml

И в твоей деятельности.

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

Вы можете скрыть пункт меню, установив isVisible как false , используя предложенное свойство isVisible в Kotlin . Но из-за этого ваш пункт меню будет удален из BottomNavigationView на Android 9 .

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

SetVisibility должен работать для вас. К вашему сведению, ниже пример в котлин.

. NavView.getMenu ( ) FindItem ( ) SetVisible (истина ) . . NavView.getMenu ( ) FindItem ( ) SetVisible (ложь ) .

В Kotlin вы можете использовать эту строку кода:

Источник

Ultimate Guide to Bottom Navigation on Android

In this tutorial, learn to add a Bottom Bar and manage Fragments with it.

Suleiman Ali Shakir

Mar 22, 2016 · 13 min read

One of the newest additions to the Material Design is the Bottom Navigation Bar. Its like the TabBar you see on iOS, and similar in functionality too.

Before getting to the tutorial, let’s get to know what Bottom Navigation is. Also let’s narrow down on the best scenarios to use it.

What is Bottom Navigation?

Bottom navigation bars make it easy to explore and switch between top-level views in a single tap. — Material Design spec

This helps developers opt for Bottom Navigation, instead of a Navigation Drawer.

If you have about four top-level navigation items, its ideal to use Bottom Navigation. Otherwise, go for a Navigation Drawer. We don’t want the Bottom Navigation looking too crowded now, do we?

This w as already common for iOS apps. But now, a lot of Android apps have started adapting this. To name a few, the YouTube app recently made the switch.

When to use?

A Bottom Navigation is best used when you have three to five top-level navigation items of similar importance.

Until now, the default, go-to navigation solution is the Navigation Drawer. Would you agree?

Grab all your screens, throw them in the Navigation Drawer and we’re done. I don’t blame you. Once upon a time, I was guilty of the same.

For just 4 navigation screens, would you use an entire Navigation Drawer for it? Besides, that huge side menu is hidden away by a tiny hamburger menu.

Think of the benefits a Bottom Navigation provides:

  • always visible — its omnipresent no matter which of the 4 screens you visit
  • simpler — lesser the options, easier to remember

So given all that, in such a scenario, a Bottom Navigation will serve you the best.

A simpler way to look at it…

If all that seems too complex, then just keep the number of navigation screens in mind.

  • 2 screens — Tabs
  • 3 to 5 screens — Bottom Navigation
  • 5 and above — Navigation Drawer

Easy enough? Now let’s move on.

Getting Started

I must admit the Bottom Navigation looks pretty cool. I noticed Aurelien Hubert has a fancy Bottom Navigation library. So let’s use that for this tutorial.

aurelhubert/ahbottomnavigation

ahbottomnavigation — A library to reproduce the behavior of the Bottom Navigation guidelines from Material Design.

NOTE:
Android Design Support Library provides a Bottom Navigation Bar too. But compared to this one, what we can do with it is currently limited. Hence, to know what all is possible with the Bottom Bar, we’ll go with Hubert’s library.

However, if you want the native solution instead, this tutorial’s got you covered.

Bottom Navigation View with Android Design Support Library

Bottom Bar (BottomNavigationView) was officially added in Design Support v25. It was first introduced in Android via the Material Design guidelines…

But seriously, read this first. This one’s got all the bells and whistles.

First, start by adding the library’s dependency to your build.gradle file.

NOTE:
I hope your app supports minSdk >14. If not, make sure you do, because this library supports 14 and above only. Seriously, why are you supporting 0.99% of the (ancient) devices!?

Adding Bottom Navigation to Layout

Make sure your parent layout is a CoordinatorLayout . This ensures the Bottom Navigation behaves correctly with Snackbar and FAB.

The FrameLayout with ID @+id/ frame is the placeholder UI to load our Fragment .

Moving onto Java

Each Bottom Navigation bar item denotes a different color. For demonstration purposes, each item click will change the Fragment ’s view color. But ideally, you’ll want to load a different Fragment for each item. I’ll tell you how to switch Fragments, a bit further into the article.

Читайте также:  Миньоны для андроид много денег

Initializing and using the Bottom Navigation is easy as one two three. I ain’t even kidding. See for yourself!

1. Create your Items

There are different constructors you can use to define your Bottom Navigation items.

At the least, you must provide a title and icon. In other words, a String and Drawable .

Both parameters can be hardcoded Strings. But for the sake of good practice, lets reference both from XML resources.

2. Add Bottom Navigation items

Once you’ve defined the number of items, its time to add them to the Bottom Navigation.

3. Set Listener

Finally, you need to listen to item clicks. So add the following to your Fragment .

I have a tiny card layout centered in my Fragment layout. Depending on the item click, I change its color.

Also, don’t forget to set your default item. This item depicts the default (home) screen which people will see.

Ideally, you’d want to change the Fragment here. The same way when creating a Navigation Drawer in Android. More on this later.

Styling Bottom Navigation

Off the bat, the library provides considerable styling options. But after recent updates, there has been a lot more.

Some of these additions include notification badges and coordinating behaviors. It also includes on-scroll Quick Return pattern.

Its all that one could ever want with the Bottom Navigation. This library is much more feature-rich than what Android Design Support Library offers. So if you want more customization options and more control, you know what to use.

Before we get to that, here’s a heads-up. We’ll be using and referencing a lot of colors. Normally, we reference colors in Android like this:

Now I’m no fan of writing such a lengthy line for fetching a simple color resource.

So I’ll write a simple method that shortens what I have to type.

Great! From now on I don’t have to write long lines. This simple method call will do to fetch my color resource.

TIP:
Hiding the complexities of a system by providing a simpler interface is known as the Facade Design Pattern.

With that out of the way, let’s look at implementing all the possible styling options.

Simple Theming

At the most basic level, the Bottom Navigation requires these attributes:

  1. Default background color
  2. Accent color — highlights active items
  3. Inactive color — (you guessed it!) color for inactive items

With such basic styling, you can expect your Bottom Navigation to look like this.

Color Ripple Effects

You can take styling a step further by using a color ripple.

Yes, I’m talking about this.

The good news is that its easy to enable a colored ripple.

The method setColoredModeColors() defines the colors for items when using color ripple.

Text Labels

Here’s what the Material Design documentation tells us. If Bottom Navigation has:

  • 3 items — display icon and text always for all items
  • 4–5 items — display text for active icon only and hide for inactive views

Now, you might have a good guess on what I’m going to say next.

“This is what the Material Design guidelines suggest, so let’s do just that”.

But this time I won’t. I disagree, and so should you. I’ll tell you why.

The Material Design guidelines aren’t always right

Whether you have 3 or 5 items in your Bottom Navigation, ALWAYS show text labels!

Buttons or links that don’t explain to you what they do. Instead, you have to click on them to find out — Mystery Meat Navigation.

I’m sure we’ve all been victims of this at some point at least. We click on a button assuming it to do something, only for it to do something else entirely!

So do yourselves, and your users a favor. Always, show text labels for your Bottom Navigation icons.

I did my part to give good UX. What about you?

Translucent Bottom Navigation

First, you create an app Theme that supports translucent navigation.

Next, in your AndroidManifest.xml, apply this Theme to your Bottom Navigation Activity .

Finally, the last step is to add one simple line to YourActivity.java.

Behaviors

The library allows on-scroll animation for the Bottom Navigation Bar. It also supports a Translucent Theme for the same. Let’s see how we can enable both.

Quick Return Animation

A View can scroll off-screen with the content and return when the user reverse scrolls. — Quick Return

This is a popular Animation pattern that helps maximize screen estate while scrolling. Usually the Quick Return animation pattern is used for Toolbars.

The good new is, this library allows us to enable the same for Bottom Navigation. You just have to add this simple line.

Translucent Navigation with Quick Return

Now you might get ambitious and want to combine both. A translucent Bottom Navigation and Quick Return pattern.

While I applaud your bravery, there’s a small hiccup in making both work together.

You already might have set up a Translucent Navigation. But once you enable Quick Return, you might notice the scroll not behaving as expected.

The Toolbar might appear clipped. No amount of fitsSystemWindows will help.

See the Toolbar? That’s the hiccup I’m talking about!

But don’t worry. I’ll tell you how to fix this.

Ideally, you’ll play around with fitsSystemWindows=true for your layout. But what worked for me is a very simple approach. Its not perfect, but it gets the job done.

All you have to do is alter your AppBarLayout . Add a View as a child to your AppBarLayout , above the Toolbar View.. This View should have a height equal to the StatusBar, which is 24dp.

Читайте также:  Ты сломал мне экран для андроид

If anyone knows how to get it working with fitsSystemWindows , do let me know!

TIP:
AppBarLayout is a vertical LinearLayout that determines scrolling behavior of its child Views.

Notification Badge

This again is simple. For the sake of demonstration, I’ll show you by creating a dummy notification.

Show notification

Let’s say I want to show a notification count of 1, for the last item. We can use the library’s AHNotification class for this.

The Builder allows us to customize the text, its color and the background. Then, remember to set that notification to the Bottom Navigation item.

Removing the Notification Icon

In the above code snippet, I used a boolean notificationVisible. It tells us whether the notification badge is currently visible or not.

A notification must be removed or dismissed once we tap the respective item. We can do this in 2 simple steps:

  1. detect the item click via OnTabSelectedListener
  2. check if notification is visible and remove it

To remove a notification, we set an EMPTY notification for that item. That is all there is to it.

Managing Bottom Navigation with Fragments

It’s pretty obvious by now that each Bottom Bar’s item manages a Fragment .

To put it in other words, you could say it’s similar to Material Tabs with a ViewPager . Except you can’t swipe.

Maintaining Fragments with ViewPager

Now that we’ve decided on using a ViewPager to handle our Fragments, we need to write an Adapter.

For that, we have two choices:

Now, depending on your use case, choosing between the two can make all the difference. But I’ll spare you all the rambling and state it simply.

Using a FragmentStatePagerAdapter is more useful when there are a large number of pages. It holds on to much less memory associated with each visited page.

Okay, our Bottom Navigation has three items, but it can go up to five. So considering the extreme scenario, we can have five resource-heavy Fragments. So you can do your app a favour and use a FragmentStatePagerAdapter .

But if you’re interested in knowing in depth, this SO post has all the answers.

Difference between FragmentPagerAdapter and FragmentStatePagerAdapter

FragmentPagerAdapter stores the whole fragment in memory, and could increase a memory overhead if a large amount of…

Creating the ViewPager Adapter

There’s a ‘smart’ implementation of FragmentStatePagerAdapter that allows us to access already existing Fragments from the Adapter. So go ahead and grab it from this GitHub gist.

Next, to actually use this, we need to create our Adapter that extends SmartFragmentStatePagerAdapter . So let’s call it BottomBarAdapter.

Nothing fancy here. Just note the List that our Adapter uses here.

NOTE:
In future if you want to fetch a particular Fragment , you can do it using pagerAdapter.getRegisteredFragment(position) .

Now that our Adapter is ready, we need to connect it to the ViewPager . But wait. Not so fast!

There is one tiny change we need to do to the ViewPager . Swiping must be disabled.

Disable swiping on ViewPager

The easiest way is to create a custom ViewPager . So let’s create a new class extending ViewPager . I call it NoSwipePager, for the lack of a better name.

NOTE:
Make sure you reference NoSwipePager in your XML layout instead of a regular ViewPager .

Once, you initialize your ViewPager in Activity , you need to explicitly disable swiping. You can do it with a single line.

With the previous step, our Adapter and ViewPager is now ready to roll. The final step is to create our Fragments, then pass them to the Adapter and finally connect the Adapter with ViewPager .

Connecting ViewPager with PagerAdapter

Let’s create a simple Fragment called DummyFragment. It accepts one argument “color”. Using a different color will tell us which Fragment instance is shown when we use the Bottom Navigation.

Once your Fragment is ready, let’s get to completing our ViewPager .

2. Initialize PagerAdapter

3. Create Fragments and add them to Adapter

4. Finally, set the ViewPager Adapter

Handling Click Events

Hang in there, we’re almost done!

Since we disabled ViewPager swiping, the only way to switch Fragments is by clicking the Bottom Navigation Items. So we need to manually handle those click events!

Don’t worry, it’s dead simple. See for yourself!

The click listener provides us a useful boolean that tells us if the current click is happening on an already selected item. So we simply need to change the Fragment when this is NOT the case.

That’s all there is to it.

Output

Just to give you a visual on how all that code works, here’s a GIF of everything put together.

Where to, from here?

The Bottom Navigation is the newest entry in Material Design. It pushes us to rethink our navigation structures.

At first, it might be confusing. But I hope this post has helped you decide when to use what.

SOURCE CODE — Available on GitHub

Suleiman19/Bottom-Navigation-Demo

Bottom-Navigation-Demo — Implementation of Bottom Navigation with Fragments, using https://github.com/aurelhubert…

Other Options

  1. Bottom Navigation Bar by roughike
    Clearly its the more popular one. But this library seems to work just as fine, so there’s no cause for alarm.
  2. Official Bottom Navigation by Design Support Library
    However, it is very limited in options in terms of styling and customization.

Wrap Up

So what do you think about Bottom Navigation? It is very common in iOS but I’m excited to see how we’re going to use it in Android.

A lot of Android apps have already adopted it (Instagram, Google+ and Quora to name a few). What about you? Let me know in the comments below.

Suleiman is a UX UI Designer & App developer who loves creating simple, usable, yet beautiful experiences for people. He’s currently pursuing his Masters in UX Design at Rutgers, NJ. Check out his portfolio .

Источник

Оцените статью