Navigation drawer with fragment in android

Fragment Navigation Drawer

In Common Navigation Paradigms cliffnotes, we discuss the various navigational structures available within Android apps. One of the most flexible is the Navigation Drawer. During the I/O Conference 2015, Google released NavigationView, which makes it far easier to create it than the previously documented instructions.

With the release of Android 5.0 Lollipop, the new material design style navigation drawer spans the full height of the screen and is displayed over the ActionBar and overlaps the translucent StatusBar . Read the material design style navigation drawer document for specs on styling your navigation drawer.

This guide explains how to setup a basic material design style drawer filled with navigation items that switch different fragments into the content area. In this way, you can define multiple fragments, and then define the list of options which will display in the drawers items list. Each item when clicked will switch the relevant fragment into the activity’s container view.

Make sure to setup the Google Design Support Library before using Google’s new NavigationView, announced as part of the Android M release. The NavigationView should be backwards compatible with all versions down to Android 2.1.

Make sure you have this Gradle dependency added to your app/build.gradle file:

Download the following icons and add them to your drawable folders by copying and pasting them into the drawable folder or using the New Image Asset dialog to create versions for each density.

If you use the New Image Asset dialog, choose a black foreground color and change the resource name.

Create a menu/drawer_view.xml file:

Note that you can set one of these elements to be default selected by using android:checked=»true» .

You can also create subheaders too and group elements together:

Next, you need to define your fragments that will be displayed within the activity. These can be any support fragments you define within your application. Make sure that all the fragments extend from androidx.fragment.app.Fragment.

In order to slide our navigation drawer over the ActionBar, we need to use the new Toolbar widget as defined in the AndroidX library. The Toolbar can be embedded into your view hierarchy which makes sure that the drawer slides over the ActionBar .

Create a new layout file res/layout/toolbar.xml with the following code:

Note that when the android:fitsSystemWindows attribute is set to true for a view, the view would be laid out as if the StatusBar and the ActionBar were present i.e. the UI on top gets padding enough to not be obscured by the navigation bar. Without this attribute, there is not enough padding factored into consideration for the ToolBar :

We want our main content view to have the navigation bar and hence android:fitsSystemWindows is set to true for the Toolbar .

To use the Toolbar as an ActionBar , you need to disable the default ActionBar . This can be done by setting the app theme in styles.xml file.

Читайте также:  Детский антивирус для андроид

Also note that normally you should decide on your color scheme by going to Material Palette and choosing a primary and dark primary color. For this example, we will pick purple-based colors as shown in the screenshot.

Note: If you forget to disable the ActionBar in styles.xml , you are likely to see a java.lang.IllegalStateException with an error message that reads This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead. If you see this message, you need to make sure to follow the previous steps.

Next, let’s setup a basic navigation drawer based on the following layout file which has the entire drawer setup in res/layout/activity_main.xml . Note that the Toolbar is added as the first child of the main content view by adding the include tag. Note: if you are using a CoordinatorLayout, it must not lie outside of the DrawerLayout. See https://stackoverflow.com/questions/32523188/coordinatorlayout-appbarlayout-navigationdrawer

Now, let’s setup the drawer in our activity. We can also setup the menu icon too.

Setup a handler to respond to click events on the navigation elements and swap out the fragment. This can be put into the activity directly:

The NavigationView also accepts a custom attribute that can reference a layout that provides a header of our layout. For instance, you can create a layout/nav_header.xml similar to the following:

You would then reference this in the layout res/layout/activity_main.xml in the NavigationView with the app:headerLayout custom attribute:

This app:headerLayout inflates the specified layout into the header automatically. This can alternatively be done at runtime with:

If you need to get a reference to the header, you need to use the new getHeaderView() method. Note, that you have to check the header count in order to avoid NPE!

In order for the hamburger icon to animate to indicate the drawer is being opened and closed, we need to use the ActionBarDrawerToggle class.

In your res/values/strings.xml add the following:

We need to tie the DrawerLayout and Toolbar together:

Next, we need to make sure we synchronize the state whenever the screen is restored or there is a configuration change (i.e screen rotation):

We also need to change the onOptionsItemSelected() method and allow the ActionBarToggle to handle the events.

The ActionBarToggle will perform the same function done previously but adds a bit more checks and allows mouse clicks on the icon to open and close the drawer. See the source code for more context.

One thing to note is that the ActionBarDrawerToggle renders a custom DrawerArrowDrawable for you for the hamburger icon.

Also, make sure to be using androidx.appcompat.app.ActionBarDrawerToggle version.

To have the status bar translucent and have our drawer slide over it, we need to set android:windowTranslucentStatus to true. Because this style is not available for pre Kitkat devices, we’ll add res/values-v19/styles.xml file for API version 19 and onwards. Note: If you modify your res/values/styles.xml directly with this android:windowTranslucentStatus line, you are likely to need to build only for SDK versions 19 or higher, which will obviously limit you from supporting many older devices.

Note many apps and developers switched to use minSdkVersion=21. It covers

85% of Android devices worldwide as of 2019.

In res/values-v19/styles.xml we can add the following:

Now if you run your app, you should see the navigation drawer and be able to select between your fragments.

One improvement made to the design support library 23.1.0 is the addition of support for custom views for the navigation drawer items. For instance, we can create a custom switch like the navigation drawer from Google Play Movies for one of the rows:

The approach is the same as adding ActionView items to the ActionBar. We simply need to define a separate layout such as the following snippet. We will call this file action_view_switch.xml :

Читайте также:  Живые обои для андроид зарядка

We then reference this layout using the app:actionLayout attribute. A title must be provided but can also be set to blank:

You can attach events directly in XML so long as your Activity will implement the method. To add an event handling to the toggle switch programmatically through Java, you will need to first get the menu instance and get access to the corresponding ActionView:

Custom widgets using app:actionViewClass can also be used too for menu items as well now too. For more details about how Action Views, see adding the SearchView to ActionBar guide.

In certain situations, especially on tablets, the navigation drawer should be a permanent fixture on the activity acting as a sidebar:

To achieve this effect, review the following links which describe one approach:

Third-party libraries may also make this easier to achieve.

There are a few third-party libraries that are still relevant as possible alternatives to using the DrawerLayout directly which provide certain material design elements automatically:

Often these are unnecessary but check them out to see the functionality they provide.

The current version of the design support library does come with its limitations. The main issue is with the system that highlights the current item in the navigation menu. The itemBackground attribute for the NavigationView does not handle the checked state of the item correctly: somehow either all items are highlighted or none of them are. This makes this attribute basically unusable for most apps.

Although many navigation drawer examples show how fragments can be used with the navigation drawer, you can also use a RelativeLayout / LinearLayout if you wish to use the drawer as an overlay to your currently displayed Activity.

Instead of you can substitute that for a

Instead of this:

You can instead use the LinearLayout container to inflate the Activity directly:

Источник

Android Navigation Drawer | Custom Fragment, Material Design

Today’s tutorial is Android Navigation Drawer With Fragments And Material Design Example.

1. Android Navigation Drawer Example | Custom Drawer

Android Navigation Drawer with fragments example guides you to create a sliding navigation menu with recyclerview.

Android Navigation Drawer with fragments tutorial uses fragments for navigation purpose.

You may have seen some application in which, when choose different options from navigation drawer, action bar shows different icons and labels for every particular fragment.

First, check the output and then follow all the steps.

Step 2: Update build.gradle(Module:app) file

Add below in build.gradle(Module:app) file

Final code for build.gradle(Module:app)

Step 3: Preparing two fragments

Create two fragments and give them name as “FriendListFragment” and “NotificationFragment.

Add below code in fragment_friend_list.xml

Add below code in FriendListFragment.java

Copy following source code in fragment_notification.xml

Copy following code in NotificationFragment.java

Step 4: Adding images

Download images and copy them into “drawable” directory.

Step 5: Updating strings.xml and styles.xml

Update string.xml as per below code

Update styles.xml as following

Step 6: Adding toolbar.xml

Create new layout resource file and give it name as “toolbar.xml

Copy below source code in it.

Step 7: Creating lv_item.xml file

Make a new layout resource file named “lv_item.xml

This file is a recyclerview item file. Add below code in it

Step 8: Creating Model

Create a new Java class named “DrawerModel” and add following code

Step 9: Making Recyclerview Adapter

Create a new Java class named “DrawerAdapter” and paste below code

Step 10: Creating DrawerFragment

Make a new fragment named DrawerFragment.

Add below source code in fragment_drawer.xml

Add following source code into DrawerFragment.java

Step 11: Description of DrawerFragment.java

In onCreateView() method, recyclerview is initialized and its onClick() method is implemented.

For recyclerview’s onClick() method implementation, a class named RecycletTouchListener and an interface named ClickListener is defined.

openFragment() method will open fragment. Here, a removeAllFragment() method is used to remove all fragments from back stack and open a fresh new fragment.

Читайте также:  Обои темно зеленые для андроид

setUpDrawer() method will be used in MainActivity.

Step 12: Updating MainActivity

Copy below code into activity_main.xml

Update MainActivity.java as per following

The End for Navigation Drawer In Android Studio example.

2. Android Navigation Drawer With Toolbar/Actionbar Menu Items

Android navigation drawer will add menu items in toolbar or action bar or header bar.

Android navigation drawer example guides to show different menu items in the toolbar or actionbar for a different fragment.

Complete all the steps from the above example, then follow steps of this tutorial.

First, watch the output of Android navigation drawer example, then we will prepare it.

Step 1: Follow all the steps from above example.

After you have completed above android sliding navigation drawer tutorial, you will have one android project with navigation drawer.

This step is must so make sure you have complete working project made from above tutorial.

Now follow below steps.

Step 2: Adding images to drawable

Download images and copy them into “drawable” directory.

Step 3: Creating menu resource directory

Create a new resource directory named “menu” inside the “res” directory as per below image.

Inside “menu,” make two xml files and name them as friend_menu.xml and notification_menu.xml

Add below source code in friend_menu.xml

Copy following in notification_menu.xml

Step 4: Updating FriendListFragment

Update FriendListFragment.java as below

Step 5: Describing update

In onCreate() method, setHasOptionsMenu() is called.

This method is necessary for implementing menu items in Toolbar.

This method must be present in the every fragments for which you want options in actionbar.

Two methods are override. One is onCreateOptionsMenu() and second is onOptionsItemSelected()

Step 6: Updating NotificationFragment

Replace source code of NotificationFragment with following

This small demo is the base for every application for all your future applications in which you want different menu items in toolbar or action bar for each fragment.

You also have access to onclick method of every items of toolbar. You can put logic in this onclick method.

3. Navigation Drawer Android Studio With Nested Fragment

Navigation drawer Android Studio example guide you to create a nested fragment.

Navigation drawer Android example will give you a professional structure to create an Android app with child fragment and sliding menu.

Complete all the steps from that example then follow steps of this tutorial.

First, see the output of navigation drawer android studio example, then we will make it.

Step 1: Follow all the steps from basic navigation drawer in Android tutorial.

After you have completed above tutorial, you will have one android project with navigation drawer.

Now follow below steps.

Step 2: Creating FriendActivity

Make a new activity named “FriendActivity.”

Copy below code into the FriendActivity.java

Add following code into activity_friend.xml

Step 3: Adding FriendNested Fragment

Create a new fragment and give the name as “FriendNestedFragment.”

Add below code in fragment_friend_nested.xml

Copy below source code in FriendNestedFragment.java

Step 4: Updating FriendListFragment

Update fragment_friend_list.xml as per below

Update FriendListFragment.java

Description of addFragment() method

This method will open a new fragment in the container box.

This method will put the fragment in the backstack before opening it. That means when the user clicks on the back button this fragment will be open if new any nested fragment or activity is opened.

Here, we have opened a FriendActivity, so when you come back from the FriendActivity, FriendNestedFragment will be opened as shown in the output video.

Step 5: Creating NotiSecondNestedFragment

Prepare a new fragment named NotiSecondNestedFragment.

Copy below source code in fragment_noti_second_nested.xml

Add following in NotiSecondNestedFragment.java

Step 6: Creating NotiNestedFragment

Make a new fragment named NotiNestedFragment.

Paste below source code in fragment_noti_nested.xml

Put following in NotiNestedFragment.java

Step 7: Updating NotificationFragment

Update fragment_notification.xml as per below

Update NotificationFragment.java as following code

Now run your project, and it should work like shown in the output video.

Источник

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