Navigation Drawer
Navigation drawer — это главное меню приложения, которое выдвигается слева направо при нажатии пользователем на значок “гамбургера”. Либо свайпом слева направо. Его еще называют “шторкой” и в открытом виде выглядит так:
Когда этот элемент интерфейса только только появился, необходимо было осуществлять много манипуляций по его добавлению на экран (если не учитывать наличие специального шаблона). Ради интереса можно ознакомиться со статьей, в которой описывается весь этот нелегкий путь.
Но вот на Google I/O 2018 была предложена совершенно новая концепция навигации по приложению, для которой уже весной 2019 года выпустили стабильную версию. Первоначально носила название Navigation Architecture Component, теперь же именуется Jetpack Navigation.
Главная цель — создание приложений по типу singleActivity.
С выходом Jetpack Navigation добавление шторки в приложении значительно упростилось, уменьшилось количество кода и настроек. Ну и, конечно же, был обновлен шаблон Navigation Drawer Activity.
В примере ниже рассмотрим добавление шторки вручную.
Алгоритм добавления шторки в интерфейс
Зависимости
В этом же файле build.gradle должно быть:
Иначе словите ошибку: 
Фрагменты
Так как основная цель Jetpack Navigation — создание приложений по типу singleActivity, основной контент будет отображаться во фрагментах.
На этом этапе нужно создать классы фрагментов и макеты к ним. В моем приложении будет три фрагмента — MainFragment , SettingsFragment , AboutFragment . По внутреннему содержанию они идентичны (все отображают TextView ), а значит будет достаточно создать один файл разметки.
Макет для MainFragment, SettingsFragment, AboutFragment — fragment_page.xml
Код для класса MainFragment
Для остальных фрагментов код идентичен, разница только в отображаемом тексте.
Навигация
Теперь для созданных фрагментов нужно выстроить навигацию.
Добавляем новую директорию в ресурсы через контекстное меню New -> Android Resource Directory. В новом окне полю Resource type задать значение navigation: 
В созданной папке добавляем новый файл nav_graph.xml .
Проще всего спроектировать навигацию через визуальный конструктор. В левом верхнем углу находится кнопка “New Destination”, с ее помощью можно добавить в граф все вышесозданные фрагменты.
При выделении фрагмента в визуальном редакторе появляется кружок в центре правого края. С помощью него выстраивается цепочка переходов от фрагмента к фрагменту.

В результате в nav_graph.xml должен получится такой код:
Обратите внимание на атрибут android:label — он отвечает за заголовок, который будет отображаться в тулбаре для каждого фрагмента.
Меню для шторки
По аналогии с навигацией, нужно добавить папку в ресурсы для меню и файл nav_drawer_menu.xml :
Обратите внимание на идентификаторы в меню — для корректной работы они должны быть идентичны идентификаторам из nav_graph.xml .
Header для шторки
Создается в папке layouts, дизайн на ваше усмотрение. Вот, что получилось у меня ( nav_header.xml ):
Объединяем все вместе в макете activity
Корневым элементом макета activity обязательно должен быть DrawerLayout, так как именно он позволяет шторке выдвигаться из края экрана. Внутри DrawerLayout’а объявляется основное содержимое экрана: toolbar, контейнер для фрагментов и сама шторка — NavigationView.
Элемент <fragment> является контейнером для наших фрагментов. Подробнее об особо важных атрибутах:
- Значение атрибута android:name=»androidx.navigation.fragment.NavHostFragment» говорит о том, что данный элемент в разметке будет являться хостом для фрагментов. Указывается обязательно в таком виде без изменений, так как хост должен быть производным от NavHostFragment, который в свою очередь обрабатывает смену фрагментов местами.
- app:defaultNavHost=»true» — позволяет перехватывать нажатие на системную кнопку “Назад”, т.е. не нужно ее дополнительно отслеживать и обрабатывать.
- app:navGraph=»@navigation/nav_graph» — связывает NavHostFragment с созданным нами графом навигации.
Для NavigationView устанавливаем ранее подготовленные файлы — header и меню, а также с помощью атрибута android:layout_gravity указываем с какой стороны она будет выезжать.
Так как в макете мы объявили реализацию toolbar , требуется отключить стандартный actionBar . Для этого заходим в values/styles.xml и меняем DarkActionBar на NoActionBar . Должно получится так:
Подключение в классе MainActivity
AppBarConfiguration — устанавливает в тулбаре иконку “гамбургера” и меняет ее на стрелку UP, если мы находимся не на главном экране приложения. Вместо графа в качестве первого параметра можно указать список фрагментов, у которых не будет происходить смена иконки “гамбургера” на стрелку UP:
Android Navigation Drawer Explained [Step By Step]
Navigation drawer used to navigate many screens or functionalities of the app by clicking on the ‘hamburger’ icon. Swiping from the left is also a way to bring the drawer into view, a screen then slides in, showing many items. You can click on these said items and go to those screens to use that feature of the app.
Navigation drawers provide access to destinations and app functionality, such as switching accounts. They can either be permanently on-screen or controlled by a navigation menu icon.
Navigation drawers are recommended for:
- Apps with five or more top-level destinations
- Apps with two or more levels of navigation hierarchy
- Quick navigation between unrelated destinations
Navigation drawer with Material Design
Navigation drawer is part of the material design. So, by including the material dependency, you can access the navigation drawer.
This is my android navigation drawer application demo,
lets create sample application on android navigation drawer using material design.
Steps to create Navigation drawer in material Design,
- Add material design dependency.
- Setup DrawerLayout.
- Setup NavigationView.
- Selecting fragment for the navigation menu Item.
Lets see the every step in details.
Step 1 — Add material design dependency
As mentioned above, drawer layout part of the material design. So lets add the material design dependency.
Step 2 — Setup DrawerLayout
In Android, DrawerLayout acts as a top-level container for window content that allows for interactive “drawer” views to be pulled out from one or both vertical edges of the window. Drawer position and layout is controlled by using the layout_gravity attribute on child views corresponding to which side of view we want the drawer to emerge from like left to right.
Also, under the DrawerLayout we need to add AppBarLayout for the Toolbar and the Fragment viewholder the FrameLayout.
app_bar_main.xml
Once created the layout files, Create ActionBarDrawerToggle for the drawerLayout listener.
ActionBarDrawerToggle: This is used with a DrawerLayout to implement the recommended functionality of Navigation Drawers. It has the following usages:
- Acts as a listener, for opening and closing of drawers.
- Provides the hamburger icons in the ToolBar/ActionBar.
- It allows for the animation between the hamburger icon and the arrow to exist.
addDrawerListener(toggle): This listener is used to keep notified of drawer events.
syncState(): will synchronize the icon’s state and display the hamburger icon or back arrow depending on whether the drawer is closed or open. Omitting this line of code won’t change the back arrow to the hamburger icon when the drawer is closed.
Important Methods Of Drawer Layout
closeDrawer(int gravity): Close the drawer view by animating it into view. We can close a drawer by passing END gravity to this method.
closeDrawers(): Close all the currently open drawer views by animating them out of view. We mainly use this method on click of any item of Navigation View.
isDrawerOpen(int drawerGravity): Used to check the drawer view is currently open or not. It returns true if the drawer view is open otherwise it returns false.
isDrawerVisible(int drawerGravity): Used to check the drawer view is currently visible on screen or not. It returns true if the drawer view is visible otherwise it returns false.
openDrawer(int gravity): Open the drawer view by animating it into view. We can open a Drawer by passing START gravity to this method.
Step 3 -Setup NavigationView
NavigationView is an easy way to display a navigation menu from a menu resource.
This is most commonly used in conjunction with DrawerLayout to implement Material navigation drawers. Navigation drawers are modal elevated dialogs that come from the start/left side, used to display in-app navigation links.
The NavigationView essentially consists of two major components,
1. HeaderLayout
This View is typically displayed at the top of the Navigation Drawer. It essentially holds the profile picture, name email address, and a background cover pic. This view is defined in a separate layout file that we’ll look at in a bit.
2. App Menu
After finishing creating the header we need to create a menu resource file that will hold the items to be displayed in the drawer. Here’s how to create the menu resource file:
Right-click the res folder →Select new →Android resource file →Choose ‘menu’ under the resource type drop-down list.
Name the file as ‘activity_main_drawer.xml’ and copy-paste the following code into the file.
Important Methods Of NavigationView
setNavigationItemSelectedListener(NavigationView.OnNavigationItemSelectedListener listener):This method is used to set a listener that will be notified when a menu item is selected.
Step 4 — Selecting fragment for the navigation menu Item
In your Activity implement the NavigationView.OnNavigationItemSelectedListener and override the onNavigationItemSelected(MenuItem item).By using the MenuItem Id we can able to launch the correct Fragment.
Display The Default Fragment
In the OnCreate() By default, we need to display the default Fragment. For that, we need to use
And Also need to start the fragment for the same,
Bonus
Navigation Drawer without Toolbar / Actionbar
Above, we have the example to create the navigation drawer with the toolbar. From that, we need to remove the toolbar layout and supportActionbar to create navigation drawer without Toolbar / Actionbar.
Delete AppBarLayout from your app_bar_main.xml
delete Toolbar from ActionBarDrawerToggle your MainActivity.java
Now you can see that Toolbar gone invisible.
That’s it. Now we created the Navigation drawer with material Design. You can download the example in github.
Как сделать боковое меню android studio
The navigation drawer is the most common feature offered by android and the navigation drawer is a UI panel that shows your app’s main navigation menu. It is also one of the important UI elements, which provides actions preferable to the users, for example changing user profile, changing settings of the application, etc. In this article, it has been discussed step by step to implement the navigation drawer in android. The code has been given in both Java and Kotlin Programming Language for Android.
The navigation drawer slides in from the left and contains the navigation destinations for the app.
The user can view the navigation drawer when the user swipes a finger from the left edge of the activity. They can also find it from the home activity by tapping the app icon in the action bar. The drawer icon is displayed on all top-level destinations that use a DrawerLayout. Have a look at the following image to get an idea about the Navigation drawer.
Steps to Implement Navigation Drawer in Android
Step 1: Create a New Android Studio Project
Create an empty activity android studio project. Refer to Android | How to Create/Start a New Project in Android Studio? on how to create an empty activity android studio project.
Step 2: Adding a dependency to the project
In this discussion, we are going to use the Material Design Navigation drawer. So add the following Material design dependency to the app-level Gradle file.
Refer to the following image if unable to locate the app-level Gradle file that invokes the dependency (under project hierarchy view). After invoking the dependency click on the “Sync Now” button. Make sure the system is connected to the network so that Android Studio downloads the required files.
Step 3: Creating a menu in the menu folder
Create the menu folder under the res folder. To implement the menu. Refer to the following video to create the layout to implement the menu.
Navigation Drawer в стиле Material Design за 5 минут
В данной статье я расскажу, как быстро добавить в ваше приложение для Android боковое меню (aka Navigation Drawer) в стиле Material Design. Для этого мы воспользуемся библиотекой, любезно предоставленной Mike Penz.
У вас получится Navigation Drawer, который:
- Соответствует последним рекомендациям по дизайну (Google Material Design Guidelines);
- Поддерживает использование нескольких Drawer (можно выдвигать второй справа);
- Поддерживает использование бейджей;
- Имеет простой и понятный интерфейс (API);
- Может выползать как под, так и поверх Status Bar;
- Позволяет менять иконки, цвета, бейджи во время выполнения;
- Использует AppCompat support library;
- Работает, начиная с API 14.
Создание проекта
В примере будет использоваться интегрированная среда разработки Android Studio от компании Google, основанная на IntelliJ IDEA, которую сама корпорация активно продвигает. Все действия можно воспроизвести используя и другие среды, например, Eclipse. Однако статья ориентирована на новичков, а они будут в большинстве своем использовать именно Android Studio, так как именно его Google теперь и предлагает при скачивании Android SDK с developer.android.com (ранее можно было скачать Eclipse).
Итак, выбираем в меню «File» -> «New Project. »:

Заполняем имя приложения, пакета, выбираем SDK.
Создавать проект мы будем с поддержкой минимального API Level равного 14, что соответствует Android 4.0 Ice Cream Sandwich, поскольку всё, что ниже, составляет менее 8% аудитории и привносит несоизмеримо большее количество головной боли:

В последних двух окнах оставляем все по умолчанию, жмем «Finish».
Android Support Library
Для того, чтобы красивый Navigation Drawer работал на версиях Android ниже 5.0 и выглядел в стиле Material Design, необходимо включить в проект библиотеку поддержки от Google, которая носит название v7 appcompat library. В текущей версии Android Studio (1.0.2) библиотека подключается по умолчанию при создании проекта. Проверьте это в файле проекта \app\build.gradle, в разделе dependencies должна быть строка (цифры могут быть не обязательно «21.0.3»):
а класс MainActivity должен наследоваться от ActionBarActivity
Также проверьте в \res\values\styles.xml, чтобы тема приложения наследовалась от Theme.AppCompat или ее вариаций без ActionBar (мы заменим ActionBar на ToolBar), например:
Подключение библиотеки MaterialDrawer
Добавьте в раздел dependencies файла \app\build.gradle строки
и нажмите появившуюся в верхней части окна кнопку «Sync Now» для синхронизации вашего проекта.
Подготовка разметки для Navigation Drawer
В главный layout приложения нужно добавить ToolBar. Приведите activity_main.xml к такому виду:
Создайте в папке layout файл drawer_header.xml со следующим содержанием
этот файл — разметка для верхней части Drawer’a, в которой находится картинка. Теперь положите в папку \res\drawable\ любую картинку с именем header.jpg, которая будет отображаться в верхней части Drawer’a, например эту: 
Файл \res\strings.xml, содержащий строковые ресурсы, приведите к следующему виду
Инициализация Navigation Drawer
В методе onCreate вашей MainActivity мы инициализируем ToolBar, добавьте после setContentView следующий код:
Затем инициализируем и сам Navigation Drawer, добавьте ниже:
В случае появления ошибок, убедитесь, что ваша секция импортов в MainActivity выглядит так:
Теперь можно запустить приложение и оценить результат:

Улучшения Navigation Drawer
Чтобы Navigation Drawer еще точнее соответствовал рекомендациям от Google, можно сделать следующие улучшения (см. полный листинг MainActivity в конце статьи):
-
Скрывать клавиатуру при открытии NavigationDrawer:
Реализацию всех этих улучшений вы можете посмотреть в полном листинге MainActivity: