Skip to content

Latest commit

 

History

History
69 lines (62 loc) · 2.41 KB

底部导航栏:.md

File metadata and controls

69 lines (62 loc) · 2.41 KB

底部导航栏的实现:

实现思路: 1.Activity 布局文件中引入 ViewPager2 控件(viewpaper2能够实现滑动切换碎片) 2.编写menu文件 提供给BottomNavigationView 用于展示 3.Activity 布局文件中引入BottomNavigationView 控件 4.编写 Fragment 用于填充到ViewPager2中 5.编写Adapter 实现 FragmentStateAdapter(碎片可以直接在adpter里面填充)

@NonNull
    @Override
    public Fragment createFragment(int position) {
        switch (position){
            case 0:
                return new ToDo();
            case 1:
                return new OutList();
            default:
                return new HadDoneList();
        }
    }

6.BottomNavigationView添加 setOnItemSelectedListener 联动ViewPager2

private void viewPaperFragment() {
        viewPager2 = findViewById(R.id.viewpager2bottom);
        bottomNavigationView = findViewById(R.id.bottom_nav_view);
        MyViewPaper2BottomAdapter myViewPaper2BottomAdapter = new MyViewPaper2BottomAdapter(this);
        viewPager2.setAdapter(myViewPaper2BottomAdapter);
        bottomNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                if (item.getItemId()==R.id.todo_view){
                    viewPager2.setCurrentItem(0);
                }
                else if (item.getItemId()==R.id.enter_out){
                    viewPager2.setCurrentItem(1);
                }
                else if (item.getItemId()==R.id.enter_done){
                    viewPager2.setCurrentItem(2);
                }
                return true;
            }
        });

7.ViewPager2 添加 registerOnPageChangeCallback 联动 BottomNavigationView

viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if (position==0){
                    bottomNavigationView.setSelectedItemId(R.id.todo_view);
                }
                else if (position==1){
                    bottomNavigationView.setSelectedItemId(R.id.enter_out);
                }
                else if (position==2){
                    bottomNavigationView.setSelectedItemId(R.id.enter_done);
                }
            }
        });