How do I implement BottomNavigationView in Android

1. Overview

There are many apps that use the bottom navigation bar on the Android side. Generally we use RadioGroup and RadiaButton to switch the user interface. Today we're going to talk about a new BottomNavigationView control that will replace RadioGroup. This control is located under the Support Design Pack and is a new control launched through Google25. Now we are using BottomNavigationView + ViewPager + Fragment to implement general navigation functions.

The final effect:

2. Implementation process

Two forms of switching are written in the demo: one is to use the viewPager to slide left and right to switch the fragment, the other is to simply hide and display the fragment through the transaction. I think everyone will. Now, using BottomNavigationView, focus on the shape of the viewPager + fragment.

First, the design package has to be introduced into the project

compile '' must be 25 or more to work.

Let's take a look at the layout:

The itemIconHint attribute can change the color of the icon. Use a selector to distinguish the selected and unselected colors.

The itemTextColor property can change the color of the text. Similarly, use the selector to distinguish the selected and unselected colors

For the memu attribute we need to create a new menu file:

All buttons in the BottomNavgationView control must be generated from this menu file. Set the monitor to control the viewpager to switch to the first few pages.

Here comes the point:

The official BottomNavigationView has an extended ShiftingMode effect by default, but does not yet support switching at code level. It is closed by default when there are 3 menu items and less, but when it reaches 4 and more it is stunned because we are going to do the sideways scrolling of ViewPager!

As you slide it, the ViewPager is toggled, and the following item is also toggled, but you can tell if this effect is cheating! ! ?

There is no possibility. I checked the information and found that the official controls don't support code-level toggle options (if you find out, please let me know). As a last resort, I can only look at the source code and activate God mode (reflection mode)!

Just call a line of code after instantiating BottomNavigationView : BottomNavigationViewHelper.disableShiftMode (bottomNavifationView);

Similarly, we'll monitor viewPager's paging monitor to change BottomNavigationView's selected state, and that's it.

Source address: