BottomNavigationView实现底部导航栏,使用Fragment+ViewPager

2,510 阅读3分钟

Demo演示

核心讲解

  • BottomNavigationView

官方描述:

Bottom navigation bars make it easy for users to explore and switch between top-level views in a single tap. They should be used when an application has three to five top-level destinations.

The bar can disappear on scroll, based on HideBottomViewOnScrollBehavior, when it is placed within a CoordinatorLayout and one of the children within the CoordinatorLayout is scrolled. This behavior is only set if the layout_behavior property is set to HideBottomViewOnScrollBehavior.

The bar contents can be populated by specifying a menu resource file. Each menu item title, icon and enabled state will be used for displaying bottom navigation bar items. Menu items can also be used for programmatically selecting which destination is currently active. It can be done using MenuItem#setChecked(true)

核心概要

  1. 底部导航栏可以很容易的切换顶部视图,当有多个页面或者Fragment时使用很方便
  2. 可以引用资源res文件夹的资源对底部导航来填充内容。每个菜单项Item的标题、图标和启用状态等都可以修饰
  3. 底部状态栏可以跳跃切换菜单项,比如从第一个跳转到最后一个,使用MenuItem#setChecked(true)来完成

Demo代码讲解

activity_main.xml

使用viewpager当作Fragment切换页面,BottomNavigationView当作导航栏在最底部

<?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=".MainActivity">

    <androidx.viewpager.widget.ViewPager
        android:layout_weight="1"
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="top"
        android:layout_marginBottom="50dp"
        tools:ignore="MissingConstraints" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

</androidx.constraintlayout.widget.ConstraintLayout>

bottom_nav_menu.xml

这里是对底部导航栏图标进行编辑,可以设置图标和标题,资源都是引用res资源菜单

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

    <item
        android:id="@+id/navigation_home"
        android:icon="@drawable/ic_home_black_24dp"
        android:title="@string/title_home" />

    <item
        android:id="@+id/navigation_show"
        android:icon="@drawable/ic_dashboard_black_24dp"
        android:title="@string/title_show" />

    <item
        android:id="@+id/navigation_notice"
        android:icon="@drawable/ic_notifications_black_24dp"
        android:title="@string/title_notice" />

</menu>

FragmentAdapter

这个Adapter是对Fragment进行适配,代码比较简单。

定义一个List对Fragment进行存储,然后加载初始化的Fragment,设置getItem使得获取相应的子项也就是切换Fragment

public class FragmentAdapter extends FragmentPagerAdapter {
    // 私有成员mFragments,加载页面碎片
    private List<Fragment> mFragments = new ArrayList<>();

    public FragmentAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
        // 加载初始化Fragment
        mFragments.add(new HomeFragment());
        mFragments.add(new ShowFragment());
        mFragments.add(new NoticeFragment());
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = null;
        switch (position) {
            case 0:
                fragment = mFragments.get(0);
                break;
            case 1:
                fragment = mFragments.get(1);

                break;
            case 2:
                fragment = mFragments.get(2);
                break;
            case 3:
                fragment = mFragments.get(3);
                break;
            default:
        }
        return fragment;
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }
}

MainActivity

setNavigation()设置底部导航栏的监听事件,点监听被图标被点击后,首先是resetIcon()重置所有图标的资源为默认值,然后底部菜单栏根据被点击的item设置为被点击,最后switchMenu(MenuItem item)切换图标方法根据被点击的图标切换相应资源。

public class MainActivity extends AppCompatActivity {

    private ViewPager            mViewPager;
    private BottomNavigationView navigation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    public void initView() {
        // BottomNavigationView
        navigation = findViewById(R.id.nav_view);
        // 去除背景底色
        navigation.setItemIconTintList(null);
        // 实例化adapter,得到fragment
        FragmentAdapter fragmentAdapter = new FragmentAdapter(getSupportFragmentManager());
        mViewPager = findViewById(R.id.viewpager);
        // 建立连接
        mViewPager.setAdapter(fragmentAdapter);

        setNavigation();
    }

    /**
     * 设置底部导航栏
     */
    public void setNavigation() {

        // 底部导航栏点击事件
        navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                resetIcon();
                switchMenu(item);
                return true;
            }
        });

        //viewpager监听事件,当viewpager滑动时得到对应的fragment碎片
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                resetIcon();
                navigation.getMenu().getItem(position).setChecked(true);
                switchMenu(navigation.getMenu().getItem(position));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 导航栏切换方法
     */
    private void switchMenu(MenuItem item){
        switch (item.getItemId()) {
            case R.id.navigation_home:
                item.setIcon(R.drawable.ic_home_selected);
                mViewPager.setCurrentItem(0);
                break;
            case R.id.navigation_show:
                mViewPager.setCurrentItem(1);
                item.setIcon(R.drawable.ic_show_selected);
                break;
            case R.id.navigation_notice:
                mViewPager.setCurrentItem(2);
                item.setIcon(R.drawable.ic_notice_selected);
                break;
            default:
        }
    }

    /**
     * 重置底部导航栏图标
     */
    private void resetIcon() {
        MenuItem home = navigation.getMenu().findItem(R.id.navigation_home);
        home.setIcon(R.drawable.ic_home_black_24dp);
        home = navigation.getMenu().findItem(R.id.navigation_show);
        home.setIcon(R.drawable.ic_dashboard_black_24dp);
        home = navigation.getMenu().findItem(R.id.navigation_notice);
        home.setIcon(R.drawable.ic_notifications_black_24dp);
    }
}

Github

示例Demo在这里哦 BottomNavigationViewDemo