它可以成功构建并运行,但在虚拟设备中已停止。 这是我在 fragment 中主要布局的代码:
public class BlankFragment14 extends Fragment {
@Override
public View onCreateView( LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState ) {
return inflater.inflate(R.layout.fragment_blank_fragment14, container, false);
}
@Override
public void onCreate( @Nullable Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
BottomNavigationView bottomNav = getView( ).findViewById(R.id.bottom_navigation);
BottomNavigationView.OnNavigationItemSelectedListener navListener = null;
bottomNav.setOnNavigationItemSelectedListener(navListener);
getFragmentManager( ).beginTransaction( ).replace(R.id.fragment_container1, new ProfileFragment( )).commit( );
navListener = new BottomNavigationView.OnNavigationItemSelectedListener( ) {
@Override
public boolean onNavigationItemSelected( @NonNull MenuItem menuItem ) {
Fragment selectedFragment = null;
switch (menuItem.getItemId( )) {
case R.id.nav_profile1:
selectedFragment = new ProfileFragment( );
break;
case R.id.nav_appointment1:
selectedFragment = new AppointmentFragment( );
break;
case R.id.nav_patientdata1:
selectedFragment = new PatientdataFragment( );
break;
}
getFragmentManager( ).beginTransaction( ).replace(R.id.fragment_container1, selectedFragment).commit( );
return true;
}
};
}
}
我不知道可以工作吗?或者我必须使用 Activity 作为主要布局。
最佳答案
使用 Navigation 组件实现 BottomNavigationView。您的 MainActivity 必须具有 NavHostFragment,它可以显示其他 fragment 目标。在 MainActivity 的 onCreate 中 如下所示设置 NavController:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(myToolbar);
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
//NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
}
关于android - 我正在尝试使用 fragment 创建 BottomNavigationView,我想在主布局中使用 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59273766/