Android: BottomNavigationBar——Bottom navigation bar control

Table of contents

1. Introduction to BottomNavigationBar

2. Common methods and common classes of BottomNavigationBar

(1) Commonly used methods

1. Add menu items

2. Remove menu items

3. Set the selected listener

4. Set the currently selected item 

5. Set up badges

 6. Style and color customization

7. Animation effects 

8. Hide the bottom navigation bar.

 9. Setting mode

10.Initialize bottomNavigation

 (2) Commonly used categories

 TextBadgeItem common methods:

 ShapeBadgeItem common methods:

3. Examples of using bottomNavigation 

1. Introduction to BottomNavigationBar

        BottomNavigationBar is a bottom navigation bar control for Android applications, often used to quickly switch between different pages of the application. It provides an intuitive and easy-to-use navigation that allows users to easily access the various modules of the application.

Dependency packages:

implementation 'com.ashokvarma.android:bottom-navigation-bar:2.0.4'

2. Common methods and common classes of BottomNavigationBar

(1) Commonly used methods

        BottomNavigationBar provides a series of commonly used methods for customizing and managing the appearance and behavior of the bottom navigation bar. The following is a detailed introduction to the common methods of BottomNavigationBar and their calling examples:

1. Add menu items

  • addItem(BottomNavigationItem item): Adds a menu item to the navigation bar.

2. Remove menu items

  • removeItem(int position): Remove the menu item at the specified position from the navigation bar.

3. Set the selected listener

  • setOnTabSelectedListener(OnTabSelectedListener listener): Set the selection listener of the navigation bar.

4. Set the currently selected item 

  • setCurrentItem(int position, boolean animate): Set the currently selected menu item.
  • setFirstSelectedPosition(int position) : Set the default selected item.

5. Set up badges

  • setNotification(String text, int position): Display the badge on the menu item at the specified location.
  • removeNotification(int position): Removes the badge from the menu item at the specified location.

 6. Style and color customization

  • setBackgroundStyle(int backgroundStyle): used to set the background style of the bottom navigation bar.
  • setDefaultBackgroundColor(int color): Set the default background color of the navigation bar.
  • setAccentColor(int color): Set the color of the selected item.
  • setInactiveColor(int color): Set the color of unselected items.
  • setTitleState(int state): Set the display mode of the title. Optional values ​​are STATE_ALWAYS_SHOW, STATE_ALWAYS_HIDE and STATE_SHOW_WHEN_ACTIVE.
  • setTitleTextSize(int textSize): Set the font size of the title.

7. Animation effects 

  • setColored(boolean colored): Set whether to enable the color animation effect of the selected item.
  • setBehaviorTranslationEnabled(boolean enabled): Set whether to enable the sliding effect of the bottom navigation bar.

8. Hide the bottom navigation bar.

  • hideBottomNavigation(boolean hide): Show or hide the bottom navigation bar.

 9. Setting mode

  • setMode(int mode) :
  1. MODE_FIXED: fixed mode

    • This mode is recommended when the number of menu items in the navigation bar is less than or equal to 3.
    • In fixed mode, all menu items are evenly distributed in the bottom navigation bar and are equal in size.
  2. MODE_SHIFTING: moving mode

    • This mode is recommended when the number of menu items in the navigation bar is greater than 3.
    • In mobile mode, the currently selected menu item is highlighted, while other unselected menu items shrink and move upward.

10.Initialize bottomNavigation

  •  initialise(): used to complete the initialization of the bottom navigation bar.

 (2) Commonly used categories

  1. BottomNavigationBar: The main class of the bottom navigation bar, used to create and manage bottom navigation items. Through this class, you can set the mode, background style, menu items and other properties of the navigation bar, and listen to the selection event of the navigation item.
  2. BadgeItem: badge class , used to display badges on menu items in the navigation bar. It has two subclasses:TextBadgeItem : used to display text subtitles on menu items. ShapeBadgeItem: Used to display shape icons on menu items, such as circles, squares, etc. 
  3. BottomNavigationItem: The class of the bottom navigation item used to create each menu item. Through this class, you can set the icon, title and icon in the selected state.
  4. OnTabSelectedListener: Select the listener interface from the tab in the bottom navigation bar . By implementing this interface, the selected event of the tab can be monitored and processed in the corresponding callback method.
  5. BadgeAnimation: The badge animation class is used to define the appearance and disappearance animation effects of the badge.

 TextBadgeItem常用方法

  • setText(String text): Set the text content displayed on the corner mark.
  • setBackgroundColor(int color): Set the background color of the corner mark.
  • setTextColor(int color): Set the color of the subscript text.
  • setHideOnSelect(boolean hideOnSelect): Set whether to hide the corner mark when the menu item is selected. The default is false.
  • setAnimationDuration(long duration): Set the duration of the corner mark animation, in milliseconds.
  • show()and hide(): Manually show and hide the badge. 
  •  setShape(Shape shape): Set the shape of the corner mark.

 ShapeBadgeItem常用方法

  • setIconDrawable(Drawable icon): Set the icon of the menu item.
  • setInactiveIconDrawable(Drawable icon): Set the icon of the unselected state of the menu item. 
  • setText(String text): Set the text content of the menu item.
  •  setInactiveColor(int color): Set the color of the unselected state of the menu item.
  • setActiveColor(int color): Set the color of the selected state of the menu item.
  • setBadgeItem(BadgeItem badgeItem): Set the corner mark for the menu item.

3. Examples of using bottomNavigation 

MainActivity: 

package com.example.bottomnavigationbardemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.ashokvarma.bottomnavigation.ShapeBadgeItem;
import com.ashokvarma.bottomnavigation.TextBadgeItem;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements BottomNavigationBar.OnTabSelectedListener {
    private FragmentManager mFragmentManager;
    private BottomNavigationBar mBottomNavigationBar;
    TextBadgeItem mTextBadgeItem;
    ShapeBadgeItem mShapeBadgeItem;
    private FirstFragment firstFragment;
    private SecondFragment secondFragment;
    private ThirdFragment thirdFragment;
    private FragmentTransaction transaction;
    int curPosition;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBottomNavigationBar = findViewById(R.id.bottom_navigation_bar);
        initBottomNavigationBar();
    }

    private void initBottomNavigationBar() {
        // 设置固定模式
        mBottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);
        // 设置点击事件
        mBottomNavigationBar.setTabSelectedListener(this);
        List<BottomNavigationItem> items= getBottomNavigationItem();
        mBottomNavigationBar.addItem(items.get(0))
                .setFirstSelectedPosition(0)
                .addItem(items.get(1))
                .addItem(items.get(2))
                // 此方法应在所有自定义方法结束时调用。此方法将考虑所有更改并重新绘制选项卡。
                .initialise();
                setDefaultFragment();
    }

    private List<BottomNavigationItem> getBottomNavigationItem() {
        initBadgeItem();
        // 用来存item的集合
        List<BottomNavigationItem> items = new ArrayList<>();
        // 创建Item1
        BottomNavigationItem homeItem = new BottomNavigationItem(R.drawable.home,"首页");
        // 设置被点击时的颜色
        homeItem.setActiveColor(R.color.purple_500).setBadgeItem(mShapeBadgeItem);
        // 设置没有被点中的颜色
//        homeItem.setInActiveColor(R.color.teal_200);
        // 设计没有被点中时的图片资源
//        homeItem.setInactiveIconResource(R.drawable.ic_launcher_foreground);
        items.add(homeItem);

        // 创建Item2
        BottomNavigationItem messageItem = new BottomNavigationItem(R.drawable.message,"信息");
        // 设置被点击时的颜色设置没有被点中的颜色
        messageItem.setActiveColor(R.color.purple_500)
//        .setInActiveColor(R.color.teal_200)
        .setBadgeItem(mTextBadgeItem);

//        .setInactiveIconResource(R.drawable.ic_launcher_foreground);
        items.add(messageItem);

        // 创建Item2
        BottomNavigationItem personage = new BottomNavigationItem(R.drawable.person,"个人信息");
        // 设置被点击时的颜色设置没有被点中的颜色
        personage.setActiveColor(R.color.purple_500);
//                .setInActiveColor(R.color.teal_200)
//                .setInactiveIconResource(R.drawable.ic_launcher_foreground);
        items.add(personage);
        return items;
    }

    /**
     * 设置徽章
     */
    private void initBadgeItem() {
        mTextBadgeItem = new TextBadgeItem();
        mTextBadgeItem.setText("99+")
                .setTextColor("#ffffff")
                .setBorderWidth(5)
                .setBackgroundColor("#ff4083")
                .setHideOnSelect(false); // 选中是否隐藏
//                .setGravity(Gravity.TOP); // 设置位置
        mShapeBadgeItem = new ShapeBadgeItem();
        mShapeBadgeItem.setShape(ShapeBadgeItem.SHAPE_OVAL)
                .setShapeColor(Color.RED)
                .setEdgeMarginInDp(this,0) // 距离item的边距,dP
                .setSizeInDp(this, 15, 15) //宽高值,dp
                .setHideOnSelect(false)
                .setAnimationDuration(300); //隐藏和展示的动画速度,单位毫秒,和setHideOnSelect一起使用
    }
    /**
     * 设置默认开启的fragment
     */
    private void setDefaultFragment() {
        mFragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        firstFragment = new FirstFragment();
        transaction.add(R.id.tb, firstFragment);
        transaction.commit();
    }
    /**
     * 隐藏当前fragment
     *
     * @param transaction
     */
    private void hideFragment(FragmentTransaction transaction) {
        if (firstFragment != null) {
            transaction.hide(firstFragment);
        }
        if (secondFragment != null) {
            transaction.hide(secondFragment);
        }
        if (thirdFragment != null) {
            transaction.hide(thirdFragment);
        }

    }

    @Override
    public void onTabSelected(int position) {
        curPosition = position;//每次点击赋值
        //开启事务
        transaction = mFragmentManager.beginTransaction();
        // 隐藏当前的fragment
        hideFragment(transaction);
        switch (position) {
            case 0:
                if (firstFragment == null) {
                    firstFragment = new FirstFragment();
                    transaction.add(R.id.tb, firstFragment);
                } else {
                    transaction.show(firstFragment);
                }
                // transaction.replace(R.id.tb, firstFragment);
                break;
            case 1:
                if (secondFragment == null) {
                    secondFragment = new SecondFragment();
                    transaction.add(R.id.tb, secondFragment);
                } else {
                    transaction.show(secondFragment);
                }
                break;
            case 2:
                if (thirdFragment == null) {
                    thirdFragment = new ThirdFragment();
                    transaction.add(R.id.tb, thirdFragment);
                } else {
                    transaction.show(thirdFragment);
                }
                break;
        }
        // 事务提交
        transaction.commit();
    }

    @Override
    public void onTabUnselected(int position) {
        // 没有被选中时,调用该方法
    }

    @Override
    public void onTabReselected(int position) {
        // 再次选中时,调用此方法
    }

}

Code analysis:

MainActivityClass is an activity that contains a bottom navigation bar. In the method, the bottom navigation bar is initialized onCreate()by calling .initBottomNavigationBar()

In initBottomNavigationBar()method:

  • Setting the mode of the bottom navigation bar to  MODE_SHIFTINGmeans that the tabs will move as the user clicks.
  • Set the click event listener of the bottom navigation bar as the current activity ( this).
  • Call  getBottomNavigationItem() the method to obtain the tab collection of the bottom navigation bar and add it to the bottom navigation bar.
  • Call  initialise() the method to complete the initialization of the bottom navigation bar and set the default displayed fragment.

In getBottomNavigationItem()method:

  • Created three bottom navigation tabs  BottomNavigationItem.
  • The icon, text, color when clicked, color when not clicked, and icon resource when not clicked are set respectively.
  • Adds tabs to a list and returns.

In addition to this, other methods are defined:

  • initBadgeItem(): Initializes two badges ( TextBadgeItem and  ShapeBadgeItem) and sets their properties.
  • setDefaultFragment(): Set the default displayed fragment to  FirstFragment.
  • hideFragment(FragmentTransaction transaction): Hide the currently displayed fragment.
  • onTabSelected(int position): Handle the event when the tab is selected and switch different fragments according to the position.
  • onTabUnselected(int position): Handles the event of tab deselection.
  • onTabReselected(int position): Handle the event when the tab is selected again.

Summary: This code is an activity that contains a bottom navigation bar that switches to display different fragments by clicking on the bottom tab. You can modify the style of the bottom navigation bar, add more tabs, and set corresponding fragments as needed.

 FirstFragment :

package com.example.bottomnavigationbardemo;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

public class FirstFragment extends Fragment {

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.activity_first_fragment, container, false);

        return view;
    }
}

 activity_first_fragment:

<?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:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="第一个Fragment"
        android:textSize="30sp" />
</LinearLayout>

activity_main: 

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

    <FrameLayout
        android:id="@+id/tb"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <View
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:background="#eeeeee" />

    <com.ashokvarma.bottomnavigation.BottomNavigationBar
        android:id="@+id/bottom_navigation_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom" />

</LinearLayout>

Note: The codes of SecondFragment, ThirdFragment and FirstFragment are the same, and their layout files are also the same as activity_first_fragment.

running result:

 

 

 4. Summary

        BottomNavigationBar is a common user interface design pattern commonly used in mobile applications. The following is a summary of the advantages and disadvantages of BottomNavigationBar:

advantage:

1. Provide intuitive navigation: The bottom navigation bar is usually located at the bottom of the screen, allowing users to easily access main functions and navigation options. This layout is more in line with users' natural operating habits and provides an intuitive navigation experience.
2. Save screen space: Placing navigation options at the bottom can save space at the top of the screen and use it more for displaying the content of the application. Especially for large-screen devices, this design makes better use of screen space.
3. Easy to operate with fingers: Since the bottom navigation bar is close to the natural position of fingers, users can easily use their thumbs to navigate without having to frequently change the posture of the handheld device.
4. Emphasize current location: By highlighting the current activity or selected navigation option, the bottom navigation bar can help users know more clearly where they are and provide contextual navigation.

shortcoming:

1. Screen space limitation: Although the bottom navigation bar saves space at the top of the screen, it also takes up a certain height at the bottom of the screen. For some applications, this may reduce the available content display area.
2. Limitation on the number of options: A bottom navigation bar is generally suitable for applications with no more than five main functions or navigation options. If there are too many options, the navigation bar may become crowded and difficult to identify and operate.
3. Design consistency: Bottom navigation is a common design pattern, but it doesn’t work for every app. When choosing to use a bottom navigation bar, make sure it is consistent with your app’s overall design style and user expectations.

        In summary, BottomNavigationBar provides the advantages of being intuitive, space-saving, and easy to operate, but it also has some disadvantages such as screen space limitations and limited number of options. When designing your app, you need to carefully consider whether to use a bottom navigation bar and make sure it is consistent with the overall design of the app.

 

Guess you like

Origin blog.csdn.net/A125679880/article/details/130038876