How to use tablayout with bottom navigation and viewpager?

后端 未结 2 867
刺人心
刺人心 2021-01-19 17:49

I created an activity with a bottom navigation bar. I want tablayout when I want to switch to another fragment. And tablayout can con

2条回答
  •  终归单人心
    2021-01-19 18:38

    Try this to sync your BottomNavigationView and TabLayout with ViewPager

        myBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    
                int id = item.getItemId();
    
                if (id == R.id.action_one) {
                    myViewPager.setCurrentItem(0);
                }else if (id == R.id.action_two) {
                    myViewPager.setCurrentItem(1);
                }else if (id == R.id.action_three) {
                    myViewPager.setCurrentItem(2);
                }else if (id == R.id.action_four) {
                    myViewPager.setCurrentItem(3);
                }
                return false;
            }
        });
    
    
        myViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (position == 0) {
                    myBottomNavigationView.setSelectedItemId(R.id.action_one);
                }else if (position == 1) {
                    myBottomNavigationView.setSelectedItemId(R.id.action_two);
                }else if (position == 2) {
                    myBottomNavigationView.setSelectedItemId(R.id.action_three);
                }else if (position == 3) {
                    myBottomNavigationView.setSelectedItemId(R.id.action_four);
                }
            }
    
            @Override
            public void onPageSelected(int position) {
    
            }
    
            @Override
            public void onPageScrollStateChanged(int state) {
    
            }
        });
    

提交回复
热议问题