How to Code a Bottom Navigation Bar for an Android App
2021-03-18 23:07:30 Author: code.tutsplus.com(查看原文) 阅读量:265 收藏

The material design team at Google defines the functionality of bottom navigation bars in Android as follows:

Bottom navigation bars make it easy to explore and switch between top-level views in a single tap.
Tapping on a bottom navigation icon takes you directly to the associated view or refreshes the currently active view.

According to the official material design guidelines for the Android bottom navigation bar, it should be used when your app has:

  • three to five top-level destinations
  • destinations requiring direct access

An example of a popular app that implements the bottom navigation bar is the Google Discover Android app from Google, which uses it to navigate to different destinations of the app. You can see this yourself by downloading the Google Discover app from the Google Play Store (if you don't already have it on your device). The following screenshot is from the Google Discover app displaying an Android bottom navigation bar.

Android Studio Bottom Navigation Bar Tutorial Screenshot of Google Discover App With Android Bottom Bar

In this post, you'll learn how to display menu items inside a bottom navigation bar in Android. We'll use the BottomNavigationView API to perform the task. For an additional bonus, you'll also learn how to use the Android Studio templates feature to quickly bootstrap your project with a bottom navigation bar. 

A sample project (in Kotlin) for this bottom navigation bar Android tutorial can be found on our GitHub repo so you can easily follow along.

Prerequisites

To be able to follow this Android Studio bottom navigation bar tutorial, you'll need:

1. Create an Android Studio Project

Fire up Android Studio and create a new project (you can name it BottomNavigationDemo) with an empty activity called MainActivity. Make sure to also check the Include Kotlin support check box.

Bottom Navigation Bar Android Tutorial Create Android Project dialog

2. Adding the BottomNavigationView

To begin using BottomNavigationView in your project, make sure you import the design support and also the Android support artifact. Add these to your module's build.gradle file to import them. 

dependencies {
    implementation 'com.android.support:design:27.0.2'
}

Also, visit your res/layout/activlty_main.xml file to include the BottomNavigationView widget. This layout file also includes a ConstraintLayout and a FrameLayout. Note that the FrameLayout will serve as a container or placeholder for the different fragments that will be placed on it anytime a menu item is clicked in the Android bottom navigation bar. (We'll get to that shortly.)  

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="https://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.chikeandroid.bottomnavigationdemo.MainActivity">

    <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.BottomNavigationView
            android:id="@+id/navigationView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginEnd="0dp"
            android:layout_marginStart="0dp"
            android:background="?android:attr/windowBackground"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:itemBackground="@color/colorPrimary"
            app:itemIconTint="@color/white"
            app:itemTextColor="@color/white"
            app:menu="@menu/navigation"/>

</android.support.constraint.ConstraintLayout>

Here we have created a BottomNavigationView widget with the id navigationView. The official documentation says that:

BottomNavigationView represents a standard bottom navigation bar for application. It is an implementation of material design bottom navigation.
Bottom navigation bars make it easy for users to explore and switch between top-level views in a single tap. It should be used when application has three to five top-level destinations.

The important attributes you should take note of that were added to our BottomNavigationView are:

  • app:itemBackground: this attribute sets the background of our menu items to the given resource. In our case, we just gave it a background colour. 
  • app:itemIconTint: sets the tint which is applied to our menu items' icons.
  • app:itemTextColor: sets the colours to use for the different states (normal, selected, focused, etc.) of the menu item text.

To include the menu items for the bottom navigation bar, we can use the attribute app:menu with a value that points to a menu resource file. 

<android.support.design.widget.BottomNavigationView
            app:menu="@menu/navigation"/>

Here is the res/menu/navigation.xml menu resource file:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
            android:id="@+id/navigation_songs"
            android:icon="@drawable/ic_music_note"
            android:title="Songs"/>

    <item
            android:id="@+id/navigation_albums"
            android:icon="@drawable/ic_album"
            android:title="Albums"/>

    <item
            android:id="@+id/navigation_artists"
            android:icon="@drawable/ic_person"
            android:title="Artists"/>

</menu>

Here we have defined a Menu using the <menu> which serves as a container for menu items. An <item> creates a MenuItem, which represents a single item in a menu. As you can see, each <item> has an id, an icon, and a title.

3. Initialization of Components

Next, we are going to initialize an instance of BottomNavigationView. Initialization is going to happen inside onCreate() in MainActivity.kt.

import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.support.v7.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    lateinit var toolbar: ActionBar

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        toolbar = supportActionBar!!
        val bottomNavigation: BottomNavigationView = findViewById(R.id.navigationView)
    }
}

4. Testing the App

Now we can run the app!

Bottom Navigation Bar Android Tutorial First demo app showing bottom navigation

As you can see, our bottom navigation bar is showing at the bottom of the app screen. Nothing will happen if you click on any of the navigation items there—we're going to handle that part in the next section. 

5. Configuring Click Events

Now, let's see how to configure click events for each of the items in the bottom navigation bar. Remember that clicking on any item in there should take the user to a new destination in the app.

// ...
    private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        when (item.itemId) {
            R.id.navigation_songs -> {
                
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_albums -> {
             
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_artists -> {
                
                return@OnNavigationItemSelectedListener true
            }
        }
        false
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        // ... 
        bottomNavigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
    }
// ...     

Here we called the method setOnNavigationItemSelectedListener. Here is what it does according to the official documentation:

Set a listener that will be notified when a bottom navigation item is selected.

We used the when expression to perform different actions based on the menu item that was clicked—the menu item ids serve as constants for the when expression. At the end of each when branch, we return true.

We then pass our mOnNavigationItemSelectedListener listener to setOnNavigationItemSelectedListener() as an argument. 

Be aware that there is another similar method called setOnNavigationItemReselectedListener, which will be notified when the currently selected bottom navigation item is reselected.

Next, we are going to create the different pages (or Fragments) for each of the menu items in the navigation drawer so that when a menu item is clicked or tapped, it displays a different Android Fragment or page. 

6. Creating the Fragments (Pages)

We'll start with the SongsFragment.kt class, and you should follow a similar process for the remaining two fragment classes—AlbumsFragment.kt and ArtistsFragment.kt.

Here is my SongsFragment.kt:

import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

class SongsFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
            inflater.inflate(R.layout.fragment_songs, container, false)

    companion object {
        fun newInstance(): SongsFragment = SongsFragment()
    }
}

Also, here is my R.layout.fragment_songs

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Songs"
            android:gravity="center_vertical|center_horizontal"/>

</LinearLayout>

7. Launching the Fragments

When any of the menu items is clicked, we open the corresponding Fragment and also change the action bar title. 

private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
    when (item.itemId) {
        R.id.navigation_songs -> {
            toolbar.title = "Songs"
            val songsFragment = SongsFragment.newInstance()
            openFragment(songsFragment)
            return@OnNavigationItemSelectedListener true
        }
        R.id.navigation_albums -> {
            toolbar.title = "Albums"
            val albumsFragment = AlbumsFragment.newInstance()
            openFragment(albumsFragment)
            return@OnNavigationItemSelectedListener true
        }
        R.id.navigation_artists -> {
            toolbar.title = "Artists"
            val artistsFragment = ArtistsFragment.newInstance()
            openFragment(artistsFragment)
            return@OnNavigationItemSelectedListener true
        }
    }
    false
}

private fun openFragment(fragment: Fragment) {
    val transaction = supportFragmentManager.beginTransaction()
    transaction.replace(R.id.container, fragment)
    transaction.addToBackStack(null)
    transaction.commit()
}

Here we're using a method called openFragment() that simply uses the FragmentTransaction to add our fragment to the UI. 

Now run the project again to see how it all works!

Android Bottom Navigation Bar Tutorial Final app demo with click events

Anytime you click on any menu item, it will take the user to a new Fragment. 

Note that when we have more than four menu items in the bottom navigation bar—i.e. in BottomNavigationView—then the Android system automatically enables shift mode. In this mode, when any of the menu items is clicked, the other items on the right or left of the clicked item are shifted. 

Bottom Navigation Bar Tutorial Bottom bar Android example with shift mode

8. Bonus: Using Android Studio Templates

Now that you've learnt about the APIs involved to create a bottom navigation bar from scratch in Android, I'll show you a shortcut that will make it faster next time. You can simply use a template instead of coding a navigation bar from scratch. 

Android Studio provides code templates that follow the Android design and development best practices. These existing code templates (available in Java and Kotlin) can help you quickly kick-start your project. One such template can be used to create a bottom navigation bar. 

To use this handy feature for a new project, first fire up Android Studio. 

Bottom Navigation Bar Tutorial Create Android Project dialog

Enter the application name and click the Next button. You can leave the defaults as they are in the Target Android Devices dialog. 

Click the Next button again. 

Bottom Navigation Bar Tutorial Add an Activity to Mobile dialog

In the Add an Activity to Mobile dialog, select Bottom Navigation Activity. Click the Next button again after that. 

Bottom Navigation Bar Android Tutorial Configure Activity dialog

In the last dialog, you can rename the Activity, or change its layout name or title if you want. Finally, click the Finish button to accept all configurations. 

Android Studio has now helped us to create a project with a bottom navigation activity. Really cool!

You're strongly advised to explore the code generated. 

In an existing Android Studio project, to use this template, simply go to File > New > Activity > Bottom Navigation Activity.

Android Bottom Tab Bar Example Tutorial Navigation from file menu to Bottom Navigation Activity

Top Android App Templates From CodeCanyon

Note that the templates that come included with Android Studio are good for simple layouts and making basic apps, but if you want to really kick-start your app, you might consider some of the app templates available from Envato Market

They’re a huge time saver for experienced developers, helping them to cut through the slog of creating an app from scratch and focus their talents instead on the unique and customised parts of creating a new app.

Let's look at a few cool templates that will let you put your new Android bottom navigation bar coding skills to good use.

1. Android App Builder—WooCommerce, WebView, WordPress and Much More

Creating native Android apps couldn't get simpler. The Android App builder template lets you turn your online presence into easy-to-use mobile experiences. Turn your WooCommerce shop, WordPress blog, or HTML5 website into an app with no coding experience necessary. Use the included tutorial to get an idea as to how to complete your app project.

Android App Builder Template

2. RocketWeb—Configurable Android WebView App Template

Looking to create a stylish Android web view app? Save yourself some time and hassle by using the RocketWeb template. You won't need any programming skills to get the most from this download. Just open it in Android Studio and start customizing. Tweak the Kotlin bottom navigation bar for Android, colors, and a whole lot more with RocketWeb.

RocketWeb Web View Android App Template

3. Dating App for Web, iOS and Android

Connections are in the air with the Dating App template. It was built in Android Studio, X Code with Swift, so you can have an Android and iOS app. On top of the modern bottom navigation bar for Android and iOS, Dating App also features:

  • simple image gallery
  • Facebook sign up
  • upgrades, AdMob banner, and in-app purchases
  • messaging and friends system
Dating App Web Version Android App iOS App Template

4. AdForest—Classified Native Android App

Let users take the classified section on the go with AdForest. Users will be able to quickly sign up and verify their accounts with their mobile numbers. Once in, they can search for products, find nearby listings, message vendors for more information, and a whole lot more. It's as easy to set up as it is to navigate.

AdForest Classified Ads Android App Template

5. MaterialX—Android Material Design UI Components

This Android app template is the perfect bundle for developers. It features all types of useful UI design elements to complete your projects. There are more than 315 unique layouts that come in more than 31 categories. Some of the included components are:

MaterialX Android UI Component Templates

Find More Android App Templates From Envato Tuts+

The above templates are great premium options in their own right. But they're far from the only ones available to you! Our instructors have rounded up some of the best Android app templates from CodeCanyon that you should check out. No matter the niche, you can find a nice Android template that suits your needs from Envato Tuts+:

Conclusion

In this tutorial, you learned how to create a bottom navigation bar in Android using the BottomNavigationView API from scratch. We also explored how to easily and quickly use the Android Studio templates to create a bottom navigation activity. 

I highly recommend checking out the official material design guidelines for bottom navigation bar to learn more about how to properly design and use the bottom navigation bar in Android.   

To learn more about coding for Android, check out some of our other courses and tutorials here on Envato Tuts+!

This post has been updated with contributions from Nathan Umoh. Nathan is a staff writer for Envato Tuts+.


文章来源: https://code.tutsplus.com/tutorials/how-to-code-a-bottom-navigation-bar-for-an-android-app--cms-30305
如有侵权请联系:admin#unsafe.sh