BottomNavigationView ViewPager2 Fragment底部菜单导航栏

正文

底部导航栏是通过BottomNavigationView组件结合[Fragment]实现的有三个按钮的菜单导航栏

效果图



    
    

bottom_nav_menu.xml



    
    
    

Activity

viewPager2 = mBinding.viewPager2;
    navView = mBinding.navView;
    viewPager2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
    List fragments = new ArrayList<>();
    fragments.add(HomeFragment.newInstance());
    fragments.add(DashboardFragment.newInstance());
    fragments.add(HomeFragment.newInstance());
    viewPager2.setAdapter(new FragmentStateAdapter(this) {
        @NonNull
        @Override
        public Fragment createFragment(int position) {
            Fragment fragment = fragments.get(position);
            return fragment;
        }
        @Override
        public int getItemCount() {
            return fragments.size();
        }
    });
    viewPager2.setOffscreenPageLimit(3);
    viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            onPagerSelected(position);
        }
    });
  navView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
      @Override
      public boolean onNavigationItemSelected(@NonNull MenuItem item) {
          switch (item.getItemId()){
              case R.id.navigation_home:
                  viewPager2.setCurrentItem(0);
                  break;
              case R.id.navigation_dashboard:
                  viewPager2.setCurrentItem(1);
                  break;
              case R.id.navigation_notifications:
                  viewPager2.setCurrentItem(2);
                  break;
          }
          return true;
      }
  });
}
private void onPagerSelected(int position) {
    switch (position) {
        case 0:
            navView.setSelectedItemId(R.id.navigation_home);
            break;
        case 1:
            navView.setSelectedItemId(R.id.navigation_dashboard);
            break;
        case 2:
            navView.setSelectedItemId(R.id.navigation_notifications);
            break;
    }
}

以上就是BottomNavigationView ViewPager2 Fragment底部菜单导航栏的详细内容,更多关于BottomNavigationView 底部菜单导航栏的资料请关注脚本之家其它相关文章!

你可能感兴趣的:(BottomNavigationView ViewPager2 Fragment底部菜单导航栏)