- 确保已经在布局文件中添加了BottomNavigationView控件,并设置了正确的id和menu菜单。
- 在MainActivity中添加以下代码,以将fragment与底部导航栏相关联:
private BottomNavigationView.OnNavigationItemSelectedListener
mOnNavigationItemSelectedListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new HomeFragment();
break;
case R.id.navigation_dashboard:
fragment = new DashboardFragment();
break;
case R.id.navigation_notifications:
fragment = new NotificationsFragment();
break;
default:
return false;
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragment).commit();
return true;
}
};
- 在MainActivity的onCreate()方法中添加以下代码,以确保第一个fragment显示:
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new HomeFragment()).commit();
}
- 如果Fragment仍然无法显示,请确保在Fragment的布局文件中包含了正确的View控件,并且该布局文件与Fragment类相关联。