如何在片段而不是活动中使用NavController(片段中带有NavHost)?
我有一个MainActivity,其中有一个带mainFragment的navController,它充当NavHost的4个片段(Feed,Notifications,Profile和Help).我的问题是这些片段中的第三个片段,其中我需要它也有自己的带有三个选项(活动,成就和编辑配置文件)的navController.我尝试创建与MainActivity中创建的方法相同的方法,在Profile片段中包含了NavHost的片段,但是android不能以这种方式接受它,并且找不到在Google上搜索的任何示例.有人知道如何解决吗?
I have a MainActivity and in it I have a navController with a mainFragment that serves as NavHost for 4 fragments (Feed, Notifications, Profile and Help). My problem is with the third of these fragments, in which I need it also has its own navController with 3 options (Activities, Achievements, and Edit Profile). I tried to create the same way I created in MainActivity, with a fragment of NavHost within the Profile fragment, but the android did not accept it in this way, and I could not find any examples searching on Google. Does anyone know how to solve it?
https://developer.android.com/reference/kotlin/androidx/navigation/NavController
它遵循我在MainActivity中实现的方式,该"bottomNavigationView"是用于在片段之间进行转换的菜单:
It follows the way I implemented in MainActivity, this "bottomNavigationView" is the menu that was made to transit among the fragments:
navController = Navigation.findNavController(this, R.id.main_fragment);
navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
navDestination = destination;
switch (destination.getId()) {
case R.id.feed:
bottomNavigationView.setCurrentActiveItem(0);
break;
case R.id.alerts:
bottomNavigationView.setCurrentActiveItem(1);
break;
case R.id.profile:
bottomNavigationView.setCurrentActiveItem(2);
break;
case R.id.help:
bottomNavigationView.setCurrentActiveItem(3);
break;
}
});
bottomNavigationView.setNavigationChangeListener((view, position) -> {
switch (position) {
case 0:
if (navDestination.getId() != R.id.feed) {
titleHeaderMain.setText(R.string.publicacao);
titleHeaderMain.setGravity(View.TEXT_ALIGNMENT_CENTER);
navController.navigate(R.id.feed);
}
break;
case 1:
if (navDestination.getId() != R.id.alerts) {
titleHeaderMain.setText(R.string.notificacoes);
navController.navigate(R.id.alerts);
}
break;
case 2:
if (navDestination.getId() != R.id.profile) {
titleHeaderMain.setText(R.string.perfil);
navController.navigate(R.id.profile);
}
break;
case 3:
if (navDestination.getId() != R.id.help) {
titleHeaderMain.setText(R.string.ajudar);
navController.navigate(R.id.help);
}
break;
}
});
您必须重新考虑您的导航路径.我有同样的问题,但是没有用.我不得不重新做.
You have to rethink your navigation path. I had the same problem but it didn't work. I had to rework on it.
我只在活动中添加底部导航,然后根据目的地隐藏或显示它.
I put bottom navigation only in activity and hide or show it depending on destination.