Android studio — Navigation Drawer Activity


Содержание

Android studio — Navigation Drawer Activity

Во многих приложениях используется выдвижная панелька под названием Navigation Drawer. Все ее видели, но не все знают, что она именно так называется. Использование Navigation Drawer дает приложению большую удобность в использовании, расширяет функционал, а также придает Android приложению более современный вид и стиль. Но не взирая на массовое распространенное использование этой штуки, толковых уроков по ее использованию не так много, а само использование Navigation Drawer не такое уж и простое и требует определенной работы. Этот урок я делаю на базе толкового урока с Хабра, имея желание его как то обобщить, упростить и представить в более доступной и ясной форме (не гарантирую, что так и будет).

Пример Navigation Drawer в приложении Q uickMemo :

Итак, в этом уроке мы сделаем приложение, оборудованное выдвижным боковым меню Navigation Drawer с тремя пунктами для выбора, при нажатии на которые будет выполняться переход на разные экраны приложения. Эти экраны будут задаваться с помощью фрагментов, по умолчанию при запуске приложения будет запускаться первый экран.

Создаем новый проект, выбираем Blank Activity, минимальную версия Android я выберу 4+.

Сразу скачайте и поместите в соответствующие папки в drawable необходимые изображения для панели.

Начнем с работы над файлом activity_main.xml. В нем нам нужно создать специальный DrawerLayout и в нем поместить область FrameLayout для отображения выдвижной панели, а также список ListView, из которого и будет состоять Navigation Drawer. Для этого добавляем в файл следующий код:

Все строковые элементы мы создадим под конец.

Для определения вида каждого отдельного пункта списка панели, создадим отдельный файл в папке layout под названием nav_draw.xml и добавим следующее:

В качестве фона для созданного выше элемента TextView мы используем xml файл из папки drawable. Давайте его создадим. В папке drawable создаем файл под названием activated_background.xml и добавим в него следующий код:

Здесь мы активно используем ссылку на синий цвет, пока еще не существующий в приложении. Чтобы его создать, в папке values создаем файл по имени color.xml и добавляем в него код:

Изменим меню приложения, изменив код в файле menu_main.xml в папке menu:

Что касается кода приложения, то в нем необходимо реализовать такие основные моменты:

— инициализировать все используемые объекты и переменные;

— задать поведение переключателю панели Navigation Drawer;

— настроить переход на необходимый фрагмент при выборе соответствующего пункта списка панели;

Код файла java класса должен выглядеть вот так (кликаем ссылку) MainActivity.java.

Чтобы приложение заработало, осталось доработать в нем фрагменты для перехода на них с Navigation Drawer и добавить все используемые строки. Чтобы реализовать фрагменты, создаем в проекте новый пакет под названием fragments и в нем создаем 3 класса по имени ScreenOne, ScreenTwo, ScreenThree:

Код во всех троих классах одинаков, за исключением xml файла интерфейса. Код для ScreenOne.java:

Для настройки интерфейса этого класса мы ссылаемся на файл под названием screen_first, давайте его создадим. В папке layout создаем файл под названием screen_first.xml и добавим в него код:

Классы (кликаем ссылку) ScreenTwo , ScreenThree аналогичны первому ScreenOne, единственное отличие в строке ссылки на файл интерфейса:

Для второго и третьего фрагментов в папке layout нужно создать интерфейса файлы screen_second.xml и screen_third.xml, которые выглядят аналогично к тому же screen_first.xml с единственным отличием в ссылке на текстовый ресурс:

Остается только внести все используемые в проекте строковые ресурсы в файл strings.xml :

Теперь можем рискнуть протестировать приложение. Запускаем проект и смотрим на результат:

Все работает исправно, а мы научились создавать красивую и полезную выдвижную панель Navigation Drawer.

Android studio — Navigation Drawer Activity

The Navigation Architecture Component simplifies implementing navigation, while also helping you visualize your app’s navigation flow. The library provides a number of benefits, including:

  • Automatic handling of fragment transactions
  • Correctly handling up and back by default
  • Default behaviors for animations and transitions
  • Deep linking as a first class operation
  • Implementing navigation UI patterns (like navigation drawers and bottom nav) with little additional work
  • Type safety when passing information while navigating
  • Android Studio tooling for visualizing and editing the navigation flow of an app

What you’ll build

In this codelab, you will work with the sample app seen below:

All the activities and fragments have already been created for you. You will use the Navigation Component to connect them and in doing so, implement the following:

  • Visual navigation graph
  • Navigation by destination and action
  • Transition animations
  • Menu navigation, bottom navigation, and menu drawer navigation
  • Type safe argument passing
  • Deep links

Prerequisites

  • Basic Kotlin knowledge (this codelab is in Kotlin)
  • Android Studio 3.2 or higher
  • Emulator or device running API 14+

Get the Code

Clone the navigation codelab from GitHub:

Alternatively you can download the repository as a Zip file:

Get Android Studio 3.3 or higher

Make sure you are using Android Studio 3.3 or higher. This is required for the Android Studio navigation tooling.

If you need to download a recent version of Android Studio, you can do so here.

Overview of Navigation

The Navigation Component consists of three key parts, working together in harmony. They are:

  1. Navigation Graph (New XML resource) — This is a resource that contains all navigation-related information in one centralized location. This includes all the places in your app, known as destinations, and possible paths a user could take through your app.
  2. NavHostFragment (Layout XML view) — This is a special widget you add to your layout. It displays different destinations from your Navigation Graph.
  3. NavController (Kotlin/Java object) — This is an object that keeps track of the current position within the navigation graph. It orchestrates swapping destination content in the NavHostFragment as you move through a navigation graph.

When you navigate, you’ll use the NavController object, telling it where you want to go or what path you want to take in your Navigation Graph. The NavController will then show the appropriate destination in the NavHostFragment.

That’s the basic idea. Let’s see what this looks like in practice, starting with the new Navigation Graph resource.

Destinations

The Navigation Component introduces the concept of a destination. A destination is any place you can navigate to in your app, usually a fragment or an activity. These are supported out of the box, but you can also make your own custom destination types if needed.

A navigation graph is a new resource type that defines all the possible paths a user can take through an app. It shows visually all the destinations that can be reached from a given destination. Android Studio displays the graph in its Navigation Editor. Here’s part of the starting navigation graph you’ll create for your app:

Exploring the Navigation Editor

1. Open res/navigation/mobile_navigation.xml

2. Click Design to go into Design mode:

Here’s what you should see:

The navigation graph shows the available destinations. The arrows between the destinations are called actions. You’ll learn more about actions later.

3. Click on a destination to see its attributes.

4. Click on any action, represented by an arrow, to see its attributes.

Anatomy of a navigation XML file

All of the changes you make in the graphical Navigation Editor change the underlying XML file, similar to the way the Layout Editor modifies the layout XML.

Click the Text tab:

You’ll see some XML like this:

Let’s take a look at a fragment destination:

  • android:id defines an ID for the fragment that you can use to reference the destination elsewhere in this XML and your code.
  • android:name declares the fully qualified class name of the fragment to instantiate when you navigate to that destination.
  • tools:layout specifies what layout should be shown in the graphical editor.

The sample app starts with a few destinations in the graph. In this step, you’ll add a brand new destination! You must add a destination to the navigation graph before you can navigate to it.

Note: The code for each step in this codelab is included, commented out between TODO statements in the code you downloaded.

You should compare the code you write to the included commented-out code.

1. Open res/navigation/mobile_navigation.xml , and click the Design tab.

2. Click the New Destination icon, and select «settings_fragment»

The result is a new destination, which renders a preview of the fragment’s layout in the design view.

Note that you can also edit the XML file directly to add destinations:

mobile_navigation.xml

To follow our naming convention, change the id to settings_dest from the default settingsFragment .

Right now you have this awesome navigation graph, but you’re not actually using it to navigate.

Activities and Navigation

The Navigation component follows the guidance outlined in the Principles of Navigation. The Principles of Navigation recommend you use activities as entry points for your app. Activities will also contain global navigation, such as the bottom nav,

In comparison, fragments will be the actual destination-specific layouts.

To get this all to work, you need to modify your activity layouts to contain a special widget called a NavHostFragment . A NavHostFragment swaps different fragment destinations in and out as you navigate through the navigation graph.

A simple layout supporting navigation similar to the picture above looks like this. An example of this code can be found in res/layout-470dp/navigation_activity.xml :

  • This is a layout for an activity. It contains the global navigation, including a bottom nav and a toolbar
  • andro and app:defaultNavHost=»true» connect the system back button to the NavHostFragment
  • app:navGraph=»@navigation/mobile_navigation» associates the NavHostFragment with a navigation graph. This navigation graph specifies all the destinations the user can navigate to, in this NavHostFragment .

Finally, when a user does something like clicking a button, you need to trigger a navigate command. A special class called the NavController is what triggers the fragment swaps in the NavHostFragment .

Note that you pass in either a destination or action ID to navigate. These are the IDs defined in the navigation graph XML. This is an example of passing in a destination ID.

NavController is powerful because when you call methods like navigate() or popBackStack(), it translates these commands into the appropriate framework operations based on the type of destination you are navigating to or from. For example, when you call navigate() with an activity destination, the NavController calls startActivity() on your behalf.

There are a few ways to get a NavController object associated with your NavHostFragment . In Kotlin, it’s recommended you use one of the following extension functions, depending on whether you’re calling the navigation command from within a fragment, activity or view:

Your NavController is associated with a NavHostFragment . Thus whichever method you use, you must be sure that the fragment, view, or view ID is either a NavHostFragment itself, or has a NavHostFragment as a parent. Otherwise you will get an IllegalStateException .

It’s your turn to navigate using NavController . You’ll hook up the Navigate To Destination button to navigate to the flow_step_one_dest destination (which is a destination that is a FlowStepFragment ):

1. Open HomeFragment.kt

2. Hook up the navigate_destination_button in onViewCreated()

HomeFragment.kt

3. Run the app and click the Navigate To Destination button. Note that the button navigates to the flow_step_one_dest destination.

You can also use the convenience method Navigation.createNavigateOnClickListener(@IdRes destId: int, bundle: Bundle) . This method will build an OnClickListener to navigate to the given destination with a bundle of arguments to be passed to the destination.

The click listener code would look like this:

Each navigate() call has a not very exciting default transition associated with it, as seen below:

The default transition, as well as other attributes associated with the call, can be overridden by including a set of NavOptions . NavOptions uses a Builder pattern which allows you to override and set only the options you need. There’s also a ktx DSL for NavOptions, which is what you’ll be using.

For animated transitions, you can define XML animation resources in the anim resource folder and then use those animations for transitions. Some examples are included in the app code:

Add a Custom Transition

Update the code so that pressing the Navigate To Destination button shows a custom transition animation.

1. Open HomeFragment.kt

2. Define a NavOptions and pass it into the navigate() call to navigate_destination_button

3. Remove the code added in step 5, if it’s still there

4. Verify that tapping the Navigate To Destination button causes the fragment to slide onto the screen and that pressing back causes it to slide off the screen

Actions

The navigation system also allows you to navigate via actions. As previously mentioned, the lines shown in the navigation graph are visual representations of actions.

Navigation by actions has the following benefits over navigation by destination:

  • You can visualize the navigation paths through your app
  • Actions can contain additional associated attributes you can set, such as a transition animation, arguments values, and backstack behavior
  • You can use the plugin safe args to navigate, which you’ll see shortly

Here’s the visual and XML for the action that connects flow_step_one_dest and flow_step_two_dest :


  • The actions are nested within the destination — this is the destination you will navigate from
  • The action includes a destination argument referring to flow_step_two_dest; this is the ID of where you will navigate to
  • The ID for the action is «next_action»

Here is another example, of the action connecting flow_step_two_dest to home_dest :

  • The same ID next_action is used for the action connecting flow_step_two_dest to home_dest . You can navigate using the next_action id from either flow_step_one_dest or flow_step_two_dest . This is an example of how actions can provide a level of abstraction and can navigate you somewhere different depending on context.
  • The popUpTo attribute is used — this action will pop fragments off of the back-stack until you reach home_dest

Time to hook up the Navigate with Action button so that it lives up to its name!

1. Open the mobile_navigation.xml file in Design mode

2. Drag an arrow from home_dest to flow_step_one_dest :

3. With the action arrow selected (blue) change the properties of the action so that:

4. Click the Text tab

Note the newly added next_action action under the home_dest destination:

mobile_navigation.xml

5. Open HomeFragment.kt

6. Add a click listener to the navigate_action_button

HomeFragment.kt

Actions allow you to attach NavOptions in the navigation XML file, rather than specifying them programmatically.

7. Verify that tapping the Navigate To Action now navigates to the next screen.

Safe Args

The navigation component has a Gradle plugin, called safe args, that generates simple object and builder classes for type-safe access to arguments specified for destinations and actions.

Safe args allows you to get rid of code like this when passing values between destinations:

And, instead, replace it with code that has generated setters and getters.

Because of its type safety, navigation using safe args generated classes is the preferred way to navigate by action and to pass arguments during navigation.

Pass a value using safe args

1. Open the project build.gradle file and notice the safe args plugin:

build.gradle

2. Open the app/build.gradle file and notice the applied plugin:

app/build.gradle

3. Open mobile_navigation.xml, and notice how arguments are defined in the flow_step_one_dest destination.

mobile_navigation.xml

Since the XML includes an argument called flowStepNumber , specified by andro , the generated class FlowStepFragmentArgs will include a variable flowStepNumber with getters and setters.

4. Open FlowStepFragment.kt

5. Comment out the line of code shown below:

FlowStepFragment.kt

This old-style code is not type-safe. It’s better to use safe args.

6. Update FlowStepFragment to use the code generated class FlowStepFragmentArgs . This will get the FlowStepFragment arguments in a type-safe manner:

FlowStepFragment.kt

Safe Args Direction classes

You can also use safe args to navigate in a type safe way, with or without adding arguments. You do this using the generated Directions classes.

Directions classes are generated for every distinct destination with actions. The Directions class includes methods for every action a destination has.

Цукерберг рекомендует:  Node js - Практика для новичков.

For example, the navigate_action_button click listener in HomeFragment.kt could be changed to:

HomeFragment.kt

Note that in your navigation graph XML you can provide a defaultValue for each argument. If you do not then you must pass the argument into the action, as shown:

The Navigation Components include a NavigationUI class and the navigation-ui-ktx kotlin extensions. NavigationUI has static methods that associate menu items with navigation destinations, and navigation-ui-ktx is a set of extension functions that do the same. If NavigationUI finds a menu item with the same ID as a destination on the current graph, it configures the menu item to navigate to that destination.

Using NavigationUI with an Options menu

One of the easiest ways to use NavigationUI is to have it simplify option menu setup. In particular, NavigationUI simplifies handling the onOptionsItemSelected callback.

1. Open MainActivity.kt

Notice how you already have the code for inflating the menu overflow_menu in onCreateOptionsMenu

2. Open res/menu/overflow_menu.xml

3. Update your overflow menu to include the settings_dest

overflow_menu.xml

4. Open MainActivity.kt

5. Have NavigationUI handle onOptionsItemSelected with the onNavDestinationSelected helper method. If the menu item is not meant to navigate, handle with super.onOptionsItemSelected

MainActivity.kt

6. Run your app. You should have a functional ActionBar menu that navigates to the SettingsFragment.

Using NavigationUI to configure Bottom Navigation

The code already contains the XML layout code for implementing bottom navigation, which is why you see the bottom navigation bar. But it doesn’t navigate anywhere.

1. Open res/layout/navigation_activity/navigation_activity.xml (h470dp) and click the Text tab

Notice how the XML layout code for bottom navigation is there and refers to bottom_nav_menu.xml

2. Open res/menu/bottom_nav_menu.xml

Notice how there are two items for the bottom navigation and that their ids match the destinations of navigation graph destinations:

bottom_nav_menu.xml

Let’s make the bottom navigation actually do something using NavigationUI.

3. Open MainActivity.kt

MainActivity.kt

Now your bottom navigation works!

Using NavigationUI to configure a Navigation Drawer

Finally, let’s use NavigationUI to configure the side navigation and navigation drawer, including handling the ActionBar and proper up navigation. You’ll see this if you’ve got a large enough screen or if the screen’s too short for bottom navigation.

First observe how the proper layout XML code is already in the app.

1. Open both navigation_activity.xml and navigation_activity.xml (w960dp)

Notice how both layouts contain a NavigationView connected to nav_drawer_menu. In the tablet version (w960dp) the NavigationView is always on screen. On smaller devices the NavigationView is nested within a DrawerLayout.

Now to start implementing the NavigationView navigation.

2. Open MainActivity.kt

3. Implement the setupNavigationMenu method using setupWithNavController(navigationView: NavigationView, navController: NavController) . Notice how this version of the method takes a NavigationView and not a BottomNavigationView .

MainActivity.kt

Now the navigation view menu will show on the screen, but it will not affect the ActionBar.

Setting up the ActionBar requires creating an instance of AppBarConfiguration . The purpose of AppBarConfiguration is to specify the configuration options you want for your toolbars, collapsing toolbars, and action bars. Configuration options include whether the bar must handle a drawer layout and which destinations are considered top-level destinations.

Top-level destinations are the root-level destinations of your app. These destinations do not display an «up» button in the app bar, and they display the drawer icon if the destination uses a drawer layout.

4. Create an AppBarConfiguration by passing in a set of top-level destination IDs and the drawer layout.

MainActivity.kt

How to determine top-level destinations

Destinations reachable via global navigation UI, such as bottom nav or side nav, all appear to users as on the same top level of the hierarchy. Therefore, they are top level destinations. home_dest and deeplink_dest are in the bottom nav and we want the drawer icon to show on both of these destinations, so they are top-level destinations.

Note that the start destination is always considered a top-level destination. If you don’t specify a list of top-level destinations, then the only top-level destination is your start destination. You can learn more about AppBarConfiguration in the documentation.

Now that you have an AppBarConfiguration, you can call NavigationUI.setupActionBarWithNavController . This will do the following:

  • Show a title in the ActionBar based off of the destination’s label
  • Display the Up button whenever you’re not on a top-level destination
  • Display a drawer icon (hamburger icon) when you’re on a top-level destination

5. Implement setupActionBarWithNavController

MainActivity.kt

You should also have NavigationUI handle what happens when the Up button is pressed.

6. Override onSupportNavigationUp and call NavigationUI.navigateUp , using the same AppBarConfiguration .

MainActivity.kt

Note, there are a few different navigateUp methods. Make sure you are using the following import from Navigation UI, which accepts the AppBarConfiguration parameter:

7. Run your code. If you open the app in split screen, you should have a working navigation drawer. The up icon and the drawer icon should display at the appropriate times and work correctly.

The layout navigation_activity.xml (h470dp) will be used on phones in portrait mode. This layout does not include the navigation drawer and instead includes the bottom navigation, which is why you should open the app in split screen to see the navigation drawer. The reason there is not a layout with both a navigation drawer and bottom navigation is because Material Design guidelines cautions against this.

Adding new destinations to a NavigationView is easy. Once you have the navigation drawer working with up and back navigation, you just need to add the new menu item.

8. Open menu/nav_drawer_menu.xml

9. Add a new menu item for settings_dest

Now your navigation drawers shows the Settings screen as a destination. Good work!

Navigation components also include deep link support. Deep links are a way to jump into the middle of your app’s navigation, whether that’s from an actual URL link or a pending intent from a notification.

One benefit of using the navigation library to handle deep links is that it ensures users start on the right destination with the appropriate back stack from other entry points such as app widgets, notifications, or web links (covered in the next step).

Navigation provides a NavDeepLinkBuilder class to construct a PendingIntent that will take the user to a specific destination.

We’ll use the NavDeepLinkBuilder to hook up an app widget to a destination.

1. Open DeepLinkAppWidgetProvider.kt

2. Add a PendingIntent constructed with NavDeepLinkBuilder :

DeepLinkAppWidgetProvider

  • setGraph includes the navigation graph.
  • setDestination specifies where the link goes to.
  • setArguments includes any arguments you want to pass into your deep link.

By default NavDeepLinkBuilder will start your launcher Activity. You can override this behavior by passing in an activity as the context or set an explicit activity class via setComponentName() .

3. Add the Deep Link widget to your home screen. Tap and hold on the home screen to see option to add widget.

Scroll down to find widget


When you’re finished, you’ll have a deep link widget.

4. Tap the widget, and verify that the Android destination opens with the correct argument. It should say «From Widget» at the top since that is the argument you passed in DeepLinkAppWidgetProvider.

5. Verify that hitting the back button takes you to the home_dest destination.

As a convenience, you can also call NavController ‘s createDeepLink() method to use the Context and current navigation graph from the NavController .

The backstack for a deep link is determined using the navigation graph you pass in. If the explicit Activity you’ve chosen has a parent activity, those parent Activities are also included.

The backstack is generated using the destinations specified with app:startDestination . In this app we only have one activity and one level of navigation, so the backstack will take you to the home_dest destination.

More complicated navigation can include nested navigation graphs. The app:startDestination at each level of the nested graphs determines the backstack. For more information on deep links and nested graphs, check out the Principles of Navigation.

The element

One of the most common uses of a deep link is to allow a web link to open an activity in your app. Traditionally you would use an intent-filter and associate a URL with the activity you want to open.

The navigation library makes this extremely simple and allows you to map URLs directly to destinations in your navigation graph.

is an element you can add to a destination in your graph. Each element has a single required attribute: app:uri .

In addition to a direct URI match, the following features are supported:

  • URIs without a scheme are assumed to be http and https. For example, www.example.com will match http://www.example.com and https://www.example.com .
  • You can use placeholders in the form of to match one or more characters. The String value of the placeholder is available in the arguments Bundle which has a key of the same name. For example, http://www.example.com/users/ will match http://www.example.com/users/4 .
  • You can use the .* wildcard to match zero or more characters.
  • NavController will automatically handle ACTION_VIEW intents and look for matching deep links.

In this step, you’ll add a deep link to www.example.com.

1. Open mobile_navigation.xml

2. Add a element to the deeplink_dest destination.

mobile_navigation.xml

3. Open AndroidManifest.xml

4. Add the nav-graph tag. This will ensure the appropriate intent filter is generated

AndroidManifest.xml

If you’re curious to see what was generated, you can find the result in your output APK.

In the Project view, navigate to app -> build -> outputs -> apk ->debug -> app-debug.apk

Double click app-debug.apk to open in APK Analyzer. Here you’ll be able to take a look at the generated AndroidManifest.

5. Launch your app using a deep link. There are two ways to do this:

  • Use adb :
  • Navigate via the Google app. You should be able to put www.example.com/urlTest in the search bar and the disambiguation window will appear. Select Navigation codelab

Opened using the search bar

Either way, you should see the message «urlTest» on screen. This was passed through to the fragment, from the URL.

There’s one more part of the codelab app for you to experiment with, and that’s the shopping cart button.

This is a recap of the skills you’ve learned during this codelab. This step does not include comments, so try it on your own:

  1. Create a new fragment class
  2. Add the fragment as a destination to your navigation graph
  3. Have the shopping cart icon open up your new fragment class, using NavigationUI to handle the menu.

You’re familiar with the basic concepts behind the Navigation component! In this codelab you learned about:

  • Navigation graph structure
  • NavHostFragment and NavController
  • How to navigate to specific destinations
  • How to navigate by action
  • How to pass arguments between destinations, including using the new safeargs plugin
  • Navigating using menus, bottom navs, and navigation drawers
  • Navigating via deep link

You can continue to explore with this app or start using navigation in your own app.

There’s a lot more to try, including:

  • Popping destinations off the backstack (or any backstack manipulations)
  • Nested navigation graphs
  • Conditional navigation
  • Adding support for new destinations

For more about the Navigation Component check out the documentation. If you’re interested in learning about other Architecture Components, try the following codelabs:

Как настроить Head в меню Navigation Drawer Activity?

Добрый день. Создаю новое приложение для андроид и использую стандартный шаблон приложения — Navigation Drawer Activity и столкнулся с проблемой, решение которое не нашел в интернете.

Использую замену фрагментов стандартным способом, при нажатии на item элемент пункта меню:

Но каким способом можно сделать замену фрагмента нажав не на пункт меню, а например на изображение из nav_header_main.xml ? Хочу реализовать переход в профиль пользователя наподобие приложения вк, авито или же алиэкспресс (нажал на аватарку вверху меню или на логин нужно перейти в профиль), но разобраться как заменить фрагмент нажав на разметку из этого файла так и не смог. Пример кода из этого файла:

Надеюсь на вашу помощь! Огромное спасибо, заранее!)

Andro > September 18, 2020 by Belal Khan 53 Comments

Hello guys, here is another tutorial for one of the most common things in any android application, navigation drawer. So in this Android Navigation Drawer Example you will learn how you can use the Android Navigation Drawer from the predefined template.

You may already know what is Android Navigation Drawer but if you are confused in implementing it with multiple fragments then don’t worry, this android navigation drawer example will clear all your doubts. So lets begin our Android Navigation Drawer Example.

Общий Navigation Drawer для нескольких окон

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

Android Studio 2.2.3

24.01.2020, 12:45

Создание окон в navigation drawer activity
Ребят, всем привет. Пытаюсь создать фрагменты в navigation drawer activity, но не могу сделать.

Navigation drawer
Скажите, как сделать так чтобы при открытии другого activity, navigation drawer можно было так же.

Navigation Drawer
помогите найти ошибку. код главного активити package ua.com.cls; import.

Navigation Drawer
Всем привет. Подскажите в чем может быть проблема. Создал Navigation Drawer по этому примеру.

Navigation drawer
Как так подключить navigation drawer чтобы он был доступен не в одном а во всех или в нескольких.

24.01.2020, 12:49 2
24.01.2020, 12:53 3
24.01.2020, 12:58 [ТС] 4
24.01.2020, 12:58
24.01.2020, 13:05 5
24.01.2020, 13:20 [ТС] 6
24.01.2020, 13:48 7
24.01.2020, 13:52 [ТС] 8
24.01.2020, 14:33 9

тупо пустой фрагмент BlankFragment

разметка активити роли не играет, но для наглядности

24.01.2020, 18:01 10

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

Что можете подсказать? Есть ли чёткий профит от выбора архитектуры, строящейся на боковом меню и фрагментах, а не на окнах с боковыми меню?

PS: признаюсь, архитектура с разными окнами меня прельщает — т.к. будет множество объектов типа окно, просто у одних будет кнопка «Назад», а у других кнопка «Открыть меню». Этим проще в голове жонглировать, когда нужно программно воспроизвести какой-нибудь путь, открыв последовательно несколько окон.
Сейчас же мне надо жонглировать окнами с кнопкой назад, и одним большим окном с фрагментами.

24.01.2020, 18:31 11
24.01.2020, 18:38 12
25.01.2020, 11:16 13

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

Но если есть дровер и не хочется использовать фрагменты, то в природе есть архитектура на разных активити с единым дровером, пример которой и просит автор темы.
Мне попадалась статья на хабре, в которой была фраза, что обе архитектуры имеют право на существование (хотя там приводилася пример всё равно архитектуры на фрагментах). Собственно, я и хочу выяснить так ли это.

Я не пробовал, но думаю надо просто сделать одно активити с дровером, и унаследовать все прочие активити, где дровер нужен, от него. И переключаться — открывать новое активити на вершине стека, убивая все предыдущие. Но, повторюсь, я не пробовал ещё.

Добавлено через 6 минут
+ отключить анимацию открытия нового активити для красоты

Posts

Many applications like Gmail, Twitter etc will have navigation menus as shown below:

You would have wondered how to create one of them. Don’t worry! in this tutorial, I will explain you in detail on how to implement navigation drawer in Android. Apart from that, in this tutorial you will also learn on:

  • how to load images from a URL using Glide library.
  • how to open a website URL on click of a menu item.
  • how to open share via dialog with a custom message and title.

Below is the screenshot of the navigation drawer we are going to develop:

Table of Contents

Creating the Project and Adding Dependencies

1. In Android Studio, create a new project with the name “Navigation Drawer Demo”. While Adding an Activity to the module, choose Navigation Drawer Activity.

Перевод статьи «Фрагментарный Navigation Drawer»

В кратких обзорах Общих парадигм навигации мы обсуждаем различные навигационные структуры, доступные в приложениях на Android. Одной из наиболее гибких является Navigation Drawer. На конференции I/O 2015 Google выпустили в релиз NavigationView, что значительно упрощает его создание, по сравнению с прежними задокументированными инструкциями.

С релизом Android 5.0 Lolipop, navigation drawer в новом стиле material design размещается по всей высоте экрана и отображается над ActionBar, перекрывая полупрозрачный StatusBar. Прочитайте navigation drawer в стиле material design, чтобы ознакомиться с инструкциями по стилизации вашего navigation drawer.

Использование

В этом руководстве объясняется настройка drawer’а, оформленного в стиле базового material design’а и наполненного элементами навигации, которые переключают различные фрагменты в зоне контента. Таким образом, можно определить несколько фрагментов, а затем определить список вариантов, которые будут отображаться в списке элементов drawer’ов. Каждый элемент при нажатии будет внедрен в соответствующий фрагмент во view-контейнере activity.

Установка

Не забудьте установить библиотеку Design Support от Google перед тем как использовать их новый NavigationView, объявленный в качестве составляющей релиза Android M. NavigationView должен быть обратно совместим со всеми версиями Android, вплоть до 2.1.

Убедитесь, что у вас есть эта Gradle-зависимость, добавленная к вашему файлу app/build.gradle:

Загрузка иконок элементов Nav Drawer’а

Загрузите представленные ниже иконки и добавьте их в ваши папки drawable, копируя и вставляя их в папку drawable, либо используя новое диалоговое окно New Image Asset, чтобы создать версии для любой плотности пикселей.

Если вы используете диалоговое окно New Image Asset, то выберите приоритетный цвет и измените имя ресурса.

Ресурсы для настройки Drawer’а

Создайте файл menu/drawer_view.xml:

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

При этом вы можете создать подзаголовки и в то же время группировать элементы вместе:

Определение фрагментов

Далее, вы должны определить свои фрагменты, которые будут отображаться внутри drawer’а. Это могут быть любые поддерживаемые фрагменты, которые вы определили в своём приложении. Убедитесь, что все фрагменты наследуются от android.support.v4.app.Fragment.

Настройка панели инструментов

Чтобы наш navigation drawer плавно выдвинулся над ActionBar’ом, нам нужно использовать новый виджет Toolbar, как это повелось в 21’ой версии библиотеки AppCompat. Toolbar можно встроить в вашу иерархию view’ов, что гарантирует скольжение drawer’а над ActionBar’ом.

Создайте новый файл layout’а «res/layout/toolbar.xml» с помощью следующего кода:

Обратите внимание, что когда атрибут android:fitsSystemWindows установлен для view как true, view будет расположен так, как если бы присутствовали StatusBar и ActionBar, т. е. находящийся сверху UI получает такой внутренний отступ, который будет достаточным для того, чтобы UI не был сокрыт панелью навигации. Без этого атрибута величина внутреннего отступа будет недостаточно учтена при расчёте ToolBar’а:

Нам требуется, чтобы у view основного контента была панель навигации и в связи с этим атрибут android:fitsSystemWindows установлен как true для Toolbar’а.

Чтобы использовать Toolbar в роли ActionBar’а, вам нужно отключить дефолтный ActionBar. Это можно сделать путём установки темы приложения в файле styles.xml.


Также обратите внимание, что обычно цветовую схему вы должны определить посредством перехода к Material Palette и выбора основного и тёмного основного цветов. Для этого примера мы выберем цвета, основанные на фиолетовом, как показано на скриншоте.

Примечание: Если вы забыли отключить ActionBar в styles.xml, то, вероятно, вы увидите исключение java.lang.illegalStateException с сообщением об ошибке, которое гласит: «У этой Activity уже есть action bar, предоставленный оформлением окна». Не запрашивайте Window.FEATURE_ACTION_BAR, а установите вместо этого в своей теме windowActionBar к false, чтобы использовать Toolbar. Если вы видите это сообщение, вы должны убедиться, что придерживаетесь предыдущих шагов.

Настройка Drawer’а в Activity

Давайте теперь настроим главный navigation drawer, основанный на приведенном ниже файле layout’а, полная настройка drawer’а которого находится в res/layout/activity_main.xml. Обратите внимание, что Toolbar добавляется в качестве первого потомка основного контентного view посредством добавления тега include.

Давайте теперь настроим drawer в нашей activity. Мы также можем заодно настроить иконку меню.

Настройте обработчик так, чтобы он отвечал на события нажатия по элементам навигации и выгружал фрагмент. Это можно включить прямо в activity:

Добавляем navigation header

Также NavigationView принимает кастомный атрибут, который может ссылаться на layout, предоставляющий header нашего layout’а. Например, можно создать файл layout/nav_header.xml, аналогичный следующему:

Затем вы бы сослались на это в layout’е res/layout/activity_main.xml в NavigationView с помощью атрибута app:headerLayoutcustom:

Этот app:headerLayout автоматически раздувает указанный layout до header’а.

Получение ссылок на заголовки

Примечание: В версии 23.1.0 библиотеки design support NavigationView переходит на использование RecyclerView’а, и выбрасываются NPE (null-исключения) при поиске в header’е до тех пор, пока header не будет добавлен во время выполнения. Если вам нужно получить ссылку на header, то вам необходимо использовать новый метод getHeaderView(), представленный в последнем обновлении v23.1.1:

Анимируем иконку гамбургера

Чтобы иконка гамбургера воспроизводила анимацию для обозначения того, что drawer открывается и закрывается, нужно использовать класс ActionBarDrawerToggle.

В вашем файле res/values/strings.xml добавьте:

Нам нужно связать вместе DrawerLayout и Toolbar:

Затем нам необходимо убедиться, что мы синхронизируем состояние всякий раз, когда экран восстанавливается, либо когда конфигурация меняется (т. е. при повороте экрана).

При этом нам нужно изменить метод onOptionsItemSelected() и позволить ActionBarToggle обрабатывать события.

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

Также стоит отметить, что ActionBarDrawerToggle отображает вам кастомный DrawerArrowDrawable, относящийся к иконке гамбургера.

Кроме того, убедитесь, что используется версия android.support.v7.app.ActionBarDrawerToggle. android.support.v4.app.ActionBarDrawerToggle устарела.

Делаем Status Bar полупрозрачным

Чтобы получить прозрачный status bar и плавно выдвигающийся над ним drawer, нам необходимо присвоить true атрибуту android:windowTranslucentStatus. Поскольку этот стиль не доступен для устройств с pre Kitkat, мы добавим файл res/values-v19/styles.xml для API, начиная с его 19 версии.

Примечание: Если вы измените ваш res/values/styles.xml напрямую с помощью этой строчки android:windowTranslucentStatus, то, вероятно, вам понадобится выполнить компиляцию только для SDK 19’ой версии и старше, что, очевидно, ограничит вас в поддержке многих более старых устройств.

В res/values-v19/styles.xml можем добавить следующее:

Теперь, если запустите своё приложение, то должны увидеть navigation drawer и сможете выбирать из своих фрагментов.

Добавление custom view’ов navigation drawer’у

Одно из улучшений, включённых в библиотеку design support 23.1.0 — добавление поддержки custom view для элементов navigation drawer. Например, мы можем создать кастомный переключатель, наподобие navigation drawer’а от Google Play Movies для одной из этих строк:

Принцип тот же, что и при добавлении элементов ActionView в ActionBar. Нам нужно просто определить разделение layout’а, такое же, как в представленном ниже сниппете. Мы обратимся к этому файлу «action_view_switch.xml»:

Потом мы ссылаемся на этот layout, используя атрибут app:actionLayout. Нужно задать заголовок, но его можно сделать и пустым:

Вы можете подключить события непосредственно в XML, при условии, что ваша Activity будет реализовывать метод. Чтобы программно посредством Java добавить обработчик события к переключателю вам сначала понадобится получить экземпляр меню и иметь доступ к соответствующему ActionView:

Кастомные виджеты, использующие app:actionViewClass при этом тоже можно использовать для элементов меню аналогичным образом, что и сейчас. Для дополнительных сведений об Action View’ах, смотрите руководство по добавлению SearchView к ActionBar’у.

Неизменяемый Navigation Drawer

В определенных ситуациях, особенно на планшетах, navigation drawer должен быть постоянным элементом activity, действующим как sidebar:

Для достижения такого эффекта посмотрите на представленные ниже ссылки, которые описывают один подход:

Сторонние библиотеки также могут облегчить осуществление этого.

Сторонние библиотеки

Есть несколько сторонних библиотек, которые всё еще актуальны в качестве возможных альтернатив прямому использованию DrawerLayout’а, и которые автоматически предоставляют определенные элементы material design’а.

Зачастую они не являются обязательными, но проверьте их, чтобы увидеть ту функциональность, которую они обеспечивают.

Ограничения

Текущая версия библиотеки design support включает в себя ограничения. Основная проблема связана с системой, которая выделяет текущий элемент в навигационном меню. Атрибут itemBackground для NavigationView не обрабатывает корректно состояние «отмечено» для элемента: почему-то выделяются либо все элементы, либо ни один из них. Это делает данный атрибут по сути дела непригодным для большинства приложений.

Альтернатива фрагментам

Несмотря на то, что многие примеры navigation drawer’а показывают, как можно использовать фрагменты с navigation drawer, вы также можете использовать RelativeLayout/LinearLayout, если желаете воспользоваться drawer’ом как оверлеем для вашей отображаемой в данный момент Activity.

Вы можете вместо использовать

Вместо вот этого:

Вы можете использовать контейнер LinearLayout, чтобы раздуть Activity напрямую:

Ссылки

Спасибо, если дочитали до конца! Приглашаю вас в свою группу переводов материалов о программировании: https://vk.com/web_translate; в Telegram: https://telegram.me/web_translate, https://telegram.me/joinchat/EQpU2gkfzdUJ8nnOCKnVlg.

Перевёл и оформил Romanov Sergei, 16.02.2020.

Andro > Anupam Chugh — 58 Comments

In this tutorial we’ll implement a Navigation Drawer in our android application. Android navigation drawer is a sliding menu and it’s an important UI component. You will see navigation drawer in most of the android applications, it’s like navigation menu bars in the websites.

Table of Contents

Android Navigation Drawer

Android Navigation Drawer is a sliding left menu that is used to display the important links in the application. Navigation drawer makes it easy to navigate to and fro between those links. It’s not visible by default and it needs to opened either by sliding from left or clicking its icon in the ActionBar.

In broader terms, Navigation Drawer is an overlay panel, which is a replacement of an activity screen which was specifically dedicated to show all the options and links in the application.

In this android navigation drawer tutorial we’ll implement the navigation drawer using the Drawer Layout API present in Android Support Library. We’ll show 3 fragment views that can be opened from the drawer items.

Android Navigation Drawer Project Structure

Android Navigation Drawer Example

To implement the Navigation Drawer we first need to add android.support.v4.widget.DrawerLayout as the root of the activity layout as shown below.

The menu options in the navigation drawer are stored in the form of a ListView. Each option opens in the FrameLayout.

We’ve used a ToolBar in place of an ActionBar here. ToolBar has been introduced since Android 5.0 as a generalisation of ActionBar. It gives us more control and flexibility to modify and its easier to interleave with other views in the hierarchy.

The layout ToolBar is defined in the xml layout given below.

We need to use the Theme Theme.AppCompat.NoActionBar in the styles.xml when using Toolbars.

The layout for the ListView rows in the Navigation Drawer is given below.

The navigation drawer items are put in a string array in the strings.xml file as shown below.

The DataModel.java class is used to define the objects for the drawer list items.

The drawer items are stored in the form of a ListView. Hence we need to use an Adapter Class to provide that data to the activity class.

The MainActivity.java source code is given below.

In the above code getSupportActionBar().setDisplayHomeAsUpEnabled(false); is used to hide the default back button.

In this code we’ve used a DrawerItemClickListener Class that loads the respective fragment of the list item clicked using a FragmentManager. Also the the title of the ToolBar is changed to the list item clicked using setTitle(mNavigationDrawerItemTitles[position]); .

The fragment classes and their respective layouts are given below.

The layout of the above fragment is defined below.

The other two items are defined in exactly the same way as above hence we’re skipping it here.

Below is the output produced by our navigation drawer android example application.

This brings an end to android navigation drawer example tutorial. You can download the final Android Navigation Drawer Project from the below link.

Android CountDownTimer Example

Android Custom Action Bar Example Tutorial

He loves learning new stuff in Android and iOS. Shoot him queries.

Comments

how can i add header in it. if i add header it repeated again and again

hi
I am shameem
Please resolve this error in App

2020-02-20 18:06:13.889 2415-2415/com.example.newnavigation E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.newnavigation, PID: 2415
java.lang.RuntimeException: Unable to start activity ComponentInfo: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2747)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2808)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1541)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:165)
at android.app.ActivityThread.main(ActivityThread.java:6375)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802)
Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.support.v7.app.AppCompatDelegateImpl.setSupportActionBar(AppCompatDelegateImpl.java:345)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:130)
at com.example.newnavigation.MainActivity.setupToolbar(MainActivity.java:121)
at com.example.newnavigation.MainActivity.onCreate(MainActivity.java:35)
at android.app.Activity.performCreate(Activity.java:6845)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2700)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2808)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1541)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:165)
at android.app.ActivityThread.main(ActivityThread.java:6375)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802)

In your styles.xml file. Add these two items.

@color/colorPrimary
@color/colorPrimaryDark
@color/colorAccent
false
true

How can I add a home button in addition to those connect,fragment…. nd onclick it should direct me to the home page!! -Thanks

can you post tablefragment and fixturesfragment java file

01/25 11:19:08: Launching app
$ adb shell am start -n “com.example..navigation/com.example..navigation.MainActivity” -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 5828 on device emulator-5554
Application terminated.

I’m having this error program is not running properly–it is showing Unfortunately stopped

How do i set the first fragment to open when i start the app instead of the blank fragment

you may add another tag between and

i need to start navigation below the appbar,what change i need to do in your project

Hey if I need the Buttons black and the toolbar white what I nedd to change?

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)’ on a null object reference

I am getting the same error. How to solve this?

06-23 17:15:20.965 7234-8041/? V/NativeCrypto: Read error: ssl=0x7f5b4afec0: I/O error during system call, Software caused connection abort
06-23 17:15:20.975 7234-7412/? V/NativeCrypto: Read error: ssl=0x7f68287a80: I/O error during system call, Software caused connection abort
06-23 17:15:20.982 4161-5467/? V/NativeCrypto: Read error: ssl=0x7f7f833700: I/O error during system call, Software caused connection abort
06-23 17:15:20.997 7038-7318/? V/NativeCrypto: Read error: ssl=0x7f7f84e4c0: I/O error during system call, Software caused connection abort
06-23 17:19:21.623 4473-5657/? V/NativeCrypto: SSL shutdown failed: ssl=0x7f5a039700: I/O error during system call, Software caused connection abort
06-23 17:19:29.053 4473-5657/? V/NativeCrypto: SSL shutdown failed: ssl=0x7f4d7c6500: I/O error during system call, Software caused connection abort
06-23 17:20:04.820 4473-5657/? V/NativeCrypto: SSL shutdown failed: ssl=0x7f7f8ecc40: I/O error during system call, Software caused connection abort
06-23 17:20:18.837 4473-5657/? V/NativeCrypto: SSL shutdown failed: ssl=0x7f7f8ea6c0: I/O error during system call, Software caused connection abort
06-23 17:21:38.241 2872-2892/? I/OHPD: [BgDetect][PD] found PD is caused by skipped uid 10212 usg 90
06-23 17:22:09.654 4161-5210/? W/GeofencerStateMachine: Ignoring removeGeofence because network location is disabled.
06-23 17:26:38.255 2872-2892/? I/OHPD: [BgDetect][PD] found PD is caused by skipped uid 10212 usg 95
06-23 17:30:15.835 4161-5210/? W/GeofencerStateMachine: Ignoring removeGeofence because network location is disabled.
06-23 17:30:19.858 4161-5210/? W/GeofencerStateMachine: Ignoring removeGeofence because network location is disabled.
06-23 17:31:38.310 2872-2892/? I/OHPD: [BgDetect][PD] found PD is caused by skipped uid 10212 usg 98
06-23 17:36:38.614 2872-2892/? I/OHPD: [BgDetect][PD] found PD is caused by skipped uid 10212 usg 97
06-23 17:41:38.652 2872-2892/? I/OHPD: [BgDetect][PD] found PD is caused by skipped uid 10212 usg 102
06-23 17:46:38.722 2872-2892/? I/OHPD: [BgDetect][PD] found PD is caused by skipped uid 10212 usg 97
06-23 17:51:39.129 2872-2892/? I/OHPD: [BgDetect][PD] found PD is caused by skipped uid 10212 usg 102
06-23 17:56:39.193 2872-2892/? I/OHPD: [BgDetect][PD] found PD is caused by skipped uid 10212 usg 104
06-23 18:01:12.779 2872-3392/? I/InputDispatcher: Dropped event because of pending overdue app switch.
06-23 18:07:15.128 4161-5210/? W/GeofencerStateMachine: Ignoring removeGeofence because network location is disabled.
06-23 18:09:08.275 4228-4228/? D/RegisteredAidCache: Not updating routing table because NFC is off.
06-23 18:09:08.279 4228-4228/? D/RegisteredNfcid2Cache: Not updating routing table because NFC is off.
06-23 18:09:08.693 11922-11922/? I/MAMComponents: Not initializing MAM classes because the MDM package is not installed.
06-23 18:09:08.694 11922-11922/? I/MAMComponents: Not initializing MAM classes because the MDM package is not installed.
06-23 18:09:09.593 11971-11971/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bhaveyashda.nvdrawer, PID: 11971
java.lang.RuntimeException: Unable to start activity ComponentInfo: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2728)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2814)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6290)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.support.v7.app.AppCompatDelegateImplV9.setSupportActionBar(AppCompatDelegateImplV9.java:204)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:129)
at com.bhaveyashda.nvdrawer.MainActivity.setupToolbar(MainActivity.java:119)
at com.bhaveyashda.nvdrawer.MainActivity.onCreate(MainActivity.java:34)
at android.app.Activity.performCreate(Activity.java:6760)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2681)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2814)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6290)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

The above is my android monitor log, My app is not running it is getting crashed, please help

drawerItem[0] = new DataModel(R.drawable.connect, “Connect”);
drawerItem[1] = new DataModel(R.drawable.fixtures, “Fixtures”);
drawerItem[2] = new DataModel(R.drawable.table, “Table”);

The above three line are giving me error what do I have to put in the drawable folder to correct this . I have not downloaded your project instead copied the code to android studio

Переключение между фрагментами с помощью onNavigationItemSelected в новом шаблоне активности навигационного ящика (Android Studio 1.4)

IntelliJ внесла изменения в шаблон шаблона навигационного ящика в Android Studio с меньшим количеством строк кода в классе Activity. Новый класс Activity выглядит следующим образом:

Одним из наиболее заметных изменений здесь является метод:

Определение шаблона старого навигационного ящика этого метода:

onNavigationItemSelected(int position, long itemId)

Вы можете изменить этот старый шаблон, удалив внутренний PlaceHolderFragment класс, создав свои собственные фрагменты и макеты и сделав что-то вроде этого:

Но это не работает с новым шаблоном (по крайней мере, не из моих маленьких знаний). Я пробовал:

но макет для макета home также показан в макете news . Вероятно, это происходит из-за строки:

Фрагменты должны быть заменены на FrameLayout , а старый макет навигационного ящика выглядел следующим образом:

Но новый выглядит следующим образом:

Короче говоря, как можно изменить новый шаблон, чтобы иметь возможность переключаться между фрагментами?

Итак, на основе @L.L. Ответ: Я смог решить эту проблему.

Прежде всего, добавьте свой FrameLayout в ваш файл content_main.xml :

В вашем MainActivity (или другом, который вы назвали «Активность с помощью навигационного ящика» ) определите метод с именем displayView

Переключение между 3 пользовательскими фрагментами; NewsFragment, EventsFragment и GalleryFragment.


в моем меню activity_main_drawer Я изменил содержимое на это:

Возвращаясь к классу Activity, в вашем методе onNavigationItemSelected сделайте следующее:

Наконец, последний оператор в методе onCreate:

Это потому, что я хочу, чтобы первое представление, которое мой пользователь видит в новостях. Измените его так, как бы вы ни выбрали.

Обратное нажатие:

Как бы то ни было, если вы нажмете кнопку «Назад» на любом из фрагментов, приложение выйдет. Я хочу, чтобы мое приложение вернулось к фрагменту новостей (мой домашний фрагмент), когда пользователь нажимает кнопку «Назад». Поэтому я сделал это:

Объявлена ​​логическая переменная:

то в методе displayView() я сделал это:

Наконец, удалите старый метод onBackPressed и создайте новый, похожий на внешний метод onCreate() :

LearnHow to Add a Navigation Drawer in Android

Ben Jakuben
writes on February 2, 2015

Android now includes a component that makes it very easy to add a navigation drawer to an app that the user can slide in from the side. I first remember seeing this in the Facebook app in iOS, and I thought it was a pretty nifty mobile design pattern (though others some people strongly disagree). I will assume you are here because you think it is good for your app, though!

In Android this component is called the navigation drawer. The Android design guidelines have a nice section on when and how we should use the navigation drawer in an app. One of my favorite uses if for power-user features that might be confusing or overwhelming for infrequent users of the app, but that are nice to have easily accessible in a menu that can be pulled in from the side.

Android Studio now includes a project template for an app that includes a navigation drawer:

It is built on Fragments, which is a useful model to have, especially if you want a common navigation drawer across multiple screens. It might be a little more than needed for a simple app, so below I will walk through how to add a navigation drawer to an existing app from scratch. If your needs go beyond what we cover here, there is a lot of good information on the Android Developer site about how to create a Navigation Drawer.

Open or Create a Project

If you care to follow along, clone or download my super simple starter app from GitHub: OS List. (The finished source is available at the end of this article.) All you need is an Activity, though. This app will target Android 4.0 and above, but the support library that brings us the Navigation Drawer makes this available on even older versions.

Your project may already contain the required dependency to use the Android support library, but if not, add the following line to the dependencies section in the build.gradle file for your app module:

(You will probably want to use the latest version of the library.)

Update the Layout

The first thing we need to do is modify the layout for our Activity. We simply need to provide a regular layout for the Activity plus a separate layout for the navigation drawer, but both layouts are contained inside the same container: DrawerLayout.

In OS List, we have a simple RelativeLayout with a TextView and ImageView. To add a navigation drawer, we add a new root element of type android.support.v4.widget.DrawLayout .

Then we add a ListView for the side drawer view:

The ListView (or whatever View we use as the side navigation drawer), should be no more than 320dp wide, so that it does not cover the entire Activity when it is out.

You can view the entire layout file here in the completed project on GitHub.

Set the List and Adapter in the Activity

Now that we have a ListView to work with, let’s set it in the Activity. In this example we will use a simple String array as our data set for the list, and an ArrayAdapter to adapt the data. (For more information about using lists and adapters, check out Android Lists and Adapters in the Treehouse library.)

First, let’s add two member variables to our Activity:

Then we can set the ListView in onCreate() :

To add items and configure the list, let’s create a helper method that we can call inside onCreate() :

At this point we have a working navigation drawer! Hooray!

We can perform an action when each item in the side navigation list is tapped just like we would for a regular ListView. Let’s set an OnItemClickListener and simply make a Toast about each item in the list:

This is the minimum basic code we need for a navigation drawer, but there is much more we can do!

Add a Toggle Switch in the Action Bar

Opinions may vary on this, but I personally prefer a hamburger menu or some kind of icon in the Action Bar that lets me know the navigation drawer is there. We can use the default icon provided by Android with a few more changes in our Activity. We can show it by adding two lines in our onCreate() method (though it won’t do anything yet):

To get this to work correctly, we need to configure something called an ActionBarDrawerToggle.

Let’s start with a few new member variable for this new object. We need one for the toggle, one for the DrawerLayout we added to our layout, and a String that we will use to update the title in the Action Bar:

Before we forget, let’s set mDrawerLayout and mActivityTitle in onCreate() :

Using a toggle requires two String resources, so let’s add those in strings.xml in the res/values directory before we proceed:

Okay! Now we can add a new helper method that we will call from onCreate() after the drawer items have been set up:

Here is where we will initialize mDrawerToggle . Autocomplete is really helpful here; or just copy and paste from below. We want to create a new ActionBarDrawerToggle instance that uses the context, mDrawerLayout , and those two new string resources we added, and then we need to implement two methods: onDrawerOpened() and onDrawerClosed() :

When the drawer is opened, we can set a new title for the Action Bar (if we want). We also want to invalidate the options menu in case it needs to be recreated with different options for when the navigation drawer is open:

And then when it is closed we will do the opposite. Revert the title (which we stored in mActivityTitle ) and again invalidate the options menu:

At this point our toggle still won’t work. We need to add two more lines to enable the drawer indicator (the lovely hamburger menu) and then attach this new toggle object to our drawer layout. Add these two lines in setupDrawer() after mDrawerToggle is set:

Finally, we need to activate this in the onOptionsItemSelected() method. Add this block of code anywhere in the method:

Keep Everything in Sync

Notice in the animated gif above that the icon isn’t quite in sync with the drawer. We need to call one more method in the onPostCreate() lifecycle method of our Activity. Inside onPostCreate() , call mDrawerToggle.syncState() to sync the indicator to match the current state of the navigation drawer:

The other scenario we need to plan for to keep things in sync is when the configuration of the Activity changes, like, for example, going from portrait to landscape or showing the soft keyboard on the screen. We do this in the Activity’s onConfigurationChanged() method, which you may need to add:

Next Steps

At this point we have a complete, working example of a navigation drawer that can be swiped in from the side or accessed via a button in the Action Bar. There is a lot more we can customize depending on our needs, of course, but this is a powerful tool that is now very easy to use thanks to the components added to the Android support library.

Look for courses, workshops, and other tips like this in the Android section of the Treehouse library, and happy coding!

Learn in-demand programming skills and become a certified Android Developer with the Treehouse Techdegree Program. Learn more and enroll today.

51 Responses to “How to Add a Navigation Drawer in Andro >

Thank you for this nice tutorial, even if it seems to be a little bit older. This helped me finally achieve to add a navigation drawer menu with a hamburger icon. And best thing is, it works extremely smooth! Great job. Looking forward for more.

Job well done, thanks guys for making learning easier.

I am new to android and this post helps me to improve. Thanks for the informative post.

Great thanks to a great tutorial. Just one small comment here that it seems latest version of Android Studio (which I’m using) complaints about setDrawerListener() method to be deprecated. It seems that changing to addDrawerListener() takes that off, just for future reference.

Great example, how do I startactivti to a second main_activity2 and keep the bar at the top

Another great guide from the Great Ben Jakuben.
Because of Ben Jakuben and Ben Deitch I code Android freely!
The B&B of Treehouse !

Good tutorial, everything was going fine until I realized my button never changes to a hamburger icon. It’s always an arrow. Everything works but I can’t get the arrow to change to a hamburger menu. I followed everything exactly as shown.

Hi,
I have a Activity SignIn layout in my app. also, I have a “content_signin” layout.
when I place “android.support.v4.widget.DrawerLayout” codes after “” app shows the drawer but I can’t use my signIn page textboxes/buttons “It blocks them even when the drawer is closed”, however the drawer works perfect. 2- when I placed it before “” the signIn page works perfect but the drawer side menu doesn’t show up (I can see the drawer sign on top).
so, any Idea where to place the drawer layout codes?
Thank you

Hi Ben!
This is a greet Tutorial for adding Navigation Drawer. I was trying many examples before but non of them works on my app except this one. i’m appreciate your help. I currently have a sign In page in my app with text boxes and buttons but when I added your drawer to that page the other buttons don’t work anymore. but the navigation drawer works perfect.
I’m new to Android.. what might be the problem? it looks like something block my signIn page. I added drawer onCreate as you said and I initialized and took care of my signIn Text boxes onStart() event.
public void onStart() <
super.onStart();
mSendButton.setOnClickListener(new View.OnClickListener() <
public void onClick(View v) <

When I click on an item it does not call the setOnItemClickListener method, what might be the problem?

Hi Thomas! As this is an older post, I’d recommend heading to the Treehouse Community to ask your question. Treehouse students and teachers are always happy to help!

Love This Tutorial, It actually explains stuff.

now I did have a problem. getSupportActionBar() Does not work! It says it’s undefined and I don’t see it explained anywhere, is that another method we create or something the android system has?

That’s the only thing that isn’t functioning, but Other than that, Awesome Tutorial!

I agree, this was an awesome tutorial(works as of July 31, 2020). I am new to android development and don’t really enjoy reading through documentation but this one was clear enough(if you have basic knowledge about android development).

Regarding your getSupportActionBar method not being recognized. Make sure the following are true:

1. Activity must extend AppCompatActivity
2. Build.gradle for your app must have a dependency
compile ‘com.android.support:appcompat-v7:23.4.0’
3. If you get an error message that it might produce a null pointer exception then do this

if( getSupportActionBar !=null ) <
getSupportActionBar.setTitle(“”); // or whatever you want to use
>

Hope this helps
Good luck!

Hi, do u know how to send the drawer to the foreground? it goes to the back of the page when I open it ��

Hi,
This article is really helpful,

I want to knw how can i add fragments on top of the main activities content layout.

Thanks , its really very helpful.

This article is really helpful for me , i am new on Android app development.

I want a search bar as the first item of my navigation drawer.How can i do that?

In this example at place of android i want a search bar
how can i use a saerchview at that place.

Thank you sor for this great tutorial,I used all the tips you gave us in this tutorial.I just want to ask how to make the drawer navlist and the toggle on the right side not left.Please if you can help me.

Nice one.
Will plz tell me how to add icon to navigation drawer.

Very nice. Is anybody know how to add TextView (anything) to the main_activity and after calling a fragment the TextView disapear?

void adddrawerItems();
<
String[] osArray = < “Android”, “iOS”, “Windows”, “OS X”, “Linux” >;
mAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
>
i get error that
expression expected

best tutorial i have found for starting with navigation drawer. Awesome work

Nice tutorial….very helpful….I have a small doubt. Is it possible to transfer data from one fragment to other in Navigationdrawer?

thanx for this tutorial but i’want know if i can replace Listnav with activity Layout

as any simple activity

heelo sir,
i’m in problem that i want to when i click DrawerView then open listof item and hide action bar

i have given intent event inside the onitemclick of setonitemclicklistener, but its not working, why?

Thanks for the tutorial !
But the navigation drawer does not register the clicks unless you specify these two lines :
mDrawerList.bringToFront();
mDrawerLayout.requestLayout();

nice tutorial but how to add submenu? can you give me sample code.. thanks..

Hello Ben, this was a great tutorial. I wanted to ask that if I have 7 screens in my app and in every page I want to use this navigation bar with the same data in it, how should I proceed? I need all the activities as navigation drawer, but do i need to initialise navlist and list view in each and every Java class.

Hi Ben ! !
Your tutorial is really nice and i want say thank for this tutorial.
and i have question that how to add a activity in these items like in “android”,”ios” and “windows”.
when i tap on a item i see “time for an upgrade!” but i want to open an activity when i tap on these items
please share your coding.

Glad you found it useful! You can open a new Activity the same way as any other time: by using an Intent and startActivity. Here’s a quick example that you can plug in where I have the code to display “Time for an upgrade!”:

Intent intent = new Intent(this, NewActivityName.class);
startActivity(intent);

hey Ben !!
It’s show error when i add “Intent intent = new Intent(this, NewActivityName.class);
startActivity(intent);” replace with Tost (Toast.makeText(MainActivity.this, “Time for an upgrade!”, Toast.LENGTH_SHORT).show();)
that error is “remove match intent”
so how can i improve this error
help me please.

Hey Ben!
when i use codes
“Intent intent = new Intent(MainActivity.this, NewActivityName.class);
startActivity(intent);”
to open an new Activity on item click of listview, its open in separate window but i want to
open it in same windows on place of Batdroid image,
how can i do it ?.
help me please .

To select different activities by clicking one of the navigation drawer array items I replaced the code to display “Time for an upgrade!” with

@Override
public void onItemClick(AdapterView parent, View view, int position, long id) <
switch (position) <
case 0: //First item
startActivity(MainActivity.this, NewActivity.class);
break;
case 1: //Second item
Intent intent = new Intent(MainActivity.this, NewActivity.class);
startActivity(intent);
//Etc
>
>

I’ve been trough your tutorial, and it works fine.
Now I want to know how to use the drawer itens to navigate between fragments.
I find a kind of difficult to use the examples created by Android Studio, besides having other problems generating the app with gradle, that frequently can’t create the resources class “R”.

I just uploaded video with drawer + fragments. Maybe it can help you. Link:
https://www.youtube.com/watch?v=tnWdMigEd4U

The example on the Android Developer Website [1] is implementing your scenario.
As you can see, the main content view of the activity contains a FrameLayout. Here they insert/remove dynamically a fragment based on user’s input in the navigation list.

Initial startup app download link is not found. Please help!

Sorry about that! I fixed the link in the “Open or Create a Project” section. Click “OS List” for the starter files now.

Android have provided an useful and flexible interface for its users. Moreover the codes given here provides excellent results. Thanks for keeping us updated.

Wow. An innovative method to ease up the navigation in Android. Cool thing.

How to use something like this :

private void addDrawerItems() <
String[] osArray = < “Android”, “iOS”, “Windows”, “OS X”, “Linux” >;
mAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
>

But having something like : ” R.string.AndroidText ” instead of “Android”

And also have different link for each things like one separate for android, another one for iOS.

Thanks for your answer.

Regarding your first question, you could use a string-array in your strings.xml
and get the items in your .java file, as follows:

Resources res = getResources();
String[] planets = res.getStringArray(R.array.planets_array);

Read more about this on [1] :

Hello, I am new to Android Development so it is really a helpful article for me. Thanks for sharing.

I really like the hamburger to arrow animation and how it is connected to the draw position but notice most apps cover it (even Google’s) when you slide the navigation draw out. It seems odd to cover the button. Is it possibly part material design language?

The documentation for Material Design does show the navigation drawer covering the action bar: http://www.google.com/design/spec/layout/structure.html#structure-side-nav

I slightly prefer having the button show. It’s kind of a pain to get it to work as specified in the design docs, too! Have a look at this StackOverflow question and answers to see some potential solutions: http://stackoverflow.com/q/26440879/475217

Hopefully this gets easier with an update to the SDK or support library in the future. ��

Android is most widely used mobile OS now a days. Thanks for sharing useful article regarding this.

This is a great information that you have shared with us. Thanks a lot. Hope to see more in future.

Thanks, Justin! Glad you enjoyed it! �� Lots more in the works for Android at Treehouse!

Цукерберг рекомендует:  Сравнения - Сравнение слов в программировании
Понравилась статья? Поделиться с друзьями:
Все языки программирования для начинающих