Well, this is yet another Android Development guide written just for you. If you are starting out with Android development. Or, even if you are reviewing the Bottom Navigation Bar in Android. This blog post is perfect for you to get started. I have covered almost everything for in a comprehensive way. Without further ado, let us dive right in.
Quick Navigation
What is Bottom Navigation Bar in Android ?
It is also known as Bottom Navigation View.
Before going right in let us first see what really is Bottom Navigation Bar. Feel free to skip this portion if it bores you.
It is just the navigation bar for primary contents in your application. Most frequently used features of the application should be placed here. It creates much better UX for the end user.
As it was introduced in material design library for android. You can rest assure that it follows all the material design guidelines.
Let us see how we can add the bottom navigation in our project.
TECHENUM
Adding the material design library
To be able to use the bottom navigation we must first include the dependency in our app > build.gradle
file, and sync it.
Add the following line in the dependencies { }
block with the rest of the existing code.
implementation 'com.google.android.material:material:1.2.1'
Code language: Groovy (groovy)
We have added the dependency in our code now let us understand the rest of the process.
Also Read: Get Full Address From Location Coordinates in Android
TECHENUM
Setting up the layout for Bottom Navigation Bar
Now, let us first set up the layout for bottom navigation. We will be using:
CoordinatorLayout
, for the material designFrameLayout
, to hold the fragments for each menu
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://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=".MainActivity">
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_nav_view"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:layout_gravity="bottom"
app:menu="@menu/menu_bottom_dashboard" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Code language: HTML, XML (xml)
If you look closely you can see we have app:menu="@menu/menu_bottom_dashboard"
in the xml. But we have not really created it. We will take care of this in the next section.
Important attributes
app:layout_behavior
tells the layout on how to handle scroll and more. Also,
android:layout_gravity
to position the bottom navigation where to position the view on the layout. Also,
app:menu
to place items in the bottom navigation. Also,
app:itemBackground
sets the background of the bottom navigation bar. Also,
app:itemRippleColor
to change the ripple color of the item shown upon selection.
I have only mentioned some of the most important attributes. You can check out more from documentation if you like. But these should be enough for starters.
Also Read: Kotlin Coroutine in Android : Understanding the Basics
TECHENUM
Mapping the UI component to Kotlin
Now that we have defined how our UI looks let us first map everything to our Kotlin code.
Here is the code for our MainActivity
, don’t worry if you get any errors.
class MainActivity : AppCompatActivity() {
private lateinit var mBottomNavigation: BottomNavigationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mBottomNavigation = findViewById(R.id.bottom_nav_view)
mBottomNavigation.setOnNavigationItemSelectedListener {
/*when (it.itemId) {
R.id.action_first_item -> changeScreen(getString(R.string.first_action))
R.id.action_second_item -> changeScreen(getString(R.string.second_action))
R.id.action_third_item -> changeScreen(getString(R.string.third_action))
R.id.action_fourth_item -> changeScreen(getString(R.string.fourth_action))
}*/
true
}
// select the first item by default as it is not selected
/*mBottomNavigation.selectedItemId = R.id.action_first_item*/
}
/**
* This will be used later to change the fragment dynamically when we click menu.
*/
/*private fun changeScreen(string: String) {
val bundle1 = Bundle()
bundle1.putString("menu_name", string)
val frag = CommonActionFragment.newInstance(bundle1)
supportFragmentManager.beginTransaction().replace(R.id.fragment_container, frag).commit()
}*/
}
Code language: Kotlin (kotlin)
I have commented out everything we will be covering later in the tutorial. But if you already know what to do you can un-comment it.
Also Read: Android RecyclerView: How to Insert, Update and Delete Item
TECHENUM
Creating menu for Bottom Navigation Bar
Now let us create a menu file in our menu > menu_bottom_dashboard.xml
. Don’t worry if you do not see any menu subdirectory.
We can create the menu sub directory in our resources by simply doing this:
- Navigate to,
Project
pane in the left side of Android Studio - Navigate to,
app > res
, right clickNew > Android Resource Directory
- After this select
menu
fromResource type
drop down - Right click on
menu
sub directory just created and selectNew > Menu Resource File
, give it a name click OK.
Here is the content of the menu file for our tutorial
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_first_item"
android:icon="@android:drawable/ic_dialog_alert"
android:title="@string/first_action" />
<item
android:id="@+id/action_second_item"
android:icon="@android:drawable/ic_delete"
android:title="@string/second_action" />
<item
android:id="@+id/action_third_item"
android:icon="@android:drawable/ic_lock_idle_alarm"
android:title="@string/third_action" />
<item
android:id="@+id/action_fourth_item"
android:icon="@android:drawable/button_onoff_indicator_off"
android:title="@string/fourth_action" />
</menu>
Code language: HTML, XML (xml)
Notice that we have used icons but not added any icons, it is because we are using the icons provided by system ( @android:
). Also take a good look at the id
of each of the items, we will be needing this later.
And also we have extracted our strings to strings.xml
file. Here is the code for strings.xml
.
Just include the code below in your strings.xml
file.
<resources>
<string name="first_action">First Action</string>
<string name="second_action">Second Action</string>
<string name="third_action">Third Action</string>
<string name="fourth_action">Fourth Action</string>
</resources>
Code language: HTML, XML (xml)
Now that we have successfully completed basic setup. Let us look at more preparations for Bottom Navigation View.
Also Read: Learn Android Room Persistence Library for SQLite Database
TECHENUM
Preparing fragments for bottom navigation content
We cannot use Activity
with the Bottom Navigation Bar because an Activity
is not modular. For this reason we will use the Fragment
.
We can have multiple fragments displayed side by side. But for this tutorial we will be using a single fragment passing in multiple values to indicate which menu is currently active.
I have created a new CommonActionFragment
class that extends Fragment
. Look at the code below.
class CommonActionFragment : Fragment() {
companion object {
// we pass the bundle that has key value pair of things that we want
fun newInstance(args: Bundle) = CommonActionFragment().apply {
arguments = args
}
}
private lateinit var mActiveMenuName: TextView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.common_action_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// get the value passed in the bundle
val name = arguments?.getString("menu_name") ?: "No Value Passed"
// map the value and display it
mActiveMenuName = view.findViewById(R.id.active_menu_name)
mActiveMenuName.text = name
}
}
Code language: Kotlin (kotlin)
That was the code which is self explanatory and here lies the UI xml code for it.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://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=".screens.CommonActionFragment">
<TextView
android:id="@+id/active_menu_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello"
android:textAlignment="center"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Code language: HTML, XML (xml)
You can copy the code itself or follow along in your own code base. This code is for a normal fragment that I have created. Next we will display the fragment in our activity.
Also Read: Android Notification Manager: Create Notification in Android
TECHENUM
Connecting the pieces together
I will explain here what the commented code does. First go ahead and un-comment everything from the MainActivity
class.
This block of code will change the fragment in our FrameLayout
in MainActivity
of course. We will be passing in the title that will be shown in our fragment.
private fun changeScreen(title: String) {
val bundle1 = Bundle()
bundle1.putString("menu_name", title)
val frag = CommonActionFragment.newInstance(bundle1)
supportFragmentManager.beginTransaction().replace(R.id.fragment_container, frag).commit()
}
Code language: Kotlin (kotlin)
And in our listener we will be identifying which item was clicked using .getItemId()
. It will give us the id of the clicked menu we created earlier, remember ?
And we do things according to the selected menu. In our case we will be invoking the method changeScreen()
passing in the related title. Look at the code below:
mBottomNavigation.setOnNavigationItemSelectedListener {
when (it.itemId) {
R.id.action_first_item -> changeScreen(getString(R.string.first_action))
R.id.action_second_item -> changeScreen(getString(R.string.second_action))
R.id.action_third_item -> changeScreen(getString(R.string.third_action))
R.id.action_fourth_item -> changeScreen(getString(R.string.fourth_action))
}
true
}
Code language: Kotlin (kotlin)
The true at the end is just the return value, why are we not doing return true
? Well it’s just lambda
, more on this on future posts.
Also Read: Android Data Binding: Replace findViewById() And More
TECHENUM
Well that’s just it we have created a fully functional Bottom Navigation Bar in Android using material design guidelines.
Here is the output if you are interested on what we have accomplished.
If you have any questions or get stuck just comment below.