How to combine BottomNavigationView and ViewPager?
As the answer of Mr. @Chintan , I replaced :
return new FooFragment();
to
viewPager.setCurrentItem(index);
And remove loadFragment() function, it's perfectly works now. Thank you very much!
Change this code in MainActivity
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.menu_home:
viewPager.setCurrentItem(0);
break;
case R.id.menu_favorite:
viewPager.setCurrentItem(1);
break;
case R.id.menu_account:
viewPager.setCurrentItem(2);
break;
}
return true;
}
Add this code for select bottomNavigation Tab.
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
switch (position) {
case 0:
mBottomNavigation.getMenu().findItem(R.id.menu_home).setChecked(true);
break;
case 1:
mBottomNavigation.getMenu().findItem(R.id.menu_favorite).setChecked(true);
break;
case 2:
mBottomNavigation.getMenu().findItem(R.id.menu_account).setChecked(true);
break;
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});