Reputation: 1328
I have added Main activity. I have a FAB button and i am trying to navigate to one of the fragments on click of the button. But I receive java.lang.IllegalArgumentException: navigation destination XXXXX/galleryFragment is unknown to this NavController Not sure what is the reason for the exception. I am new to android development please excuse my ignorance
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
FloatingActionButton fab = findViewById(R.id.fab);
Navigation.setViewNavController(fab, navController);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Navigation.findNavController(view).navigate(R.id.galleryFragment);
}
});
}
Upvotes: 1
Views: 1716
Reputation: 151
you can store the navController
as a global variable, then don't use Navigation.findNavController
, use navController.navigate
.
NavController navController = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
navController.navigate(R.id.galleryFragment);
}
});
}
Upvotes: 1
Reputation: 199994
Navigation.findNavController(view)
only works when the View is within the NavHostFragment
(i.e., it is a view created by one of your fragments).
If your FloatingActionButton
is outside of the NavHostFragment
(such as in your activity's layout), then you need to use the same thing you're using in onCreate()
: Navigation.findNavController(this, R.id.nav_host_fragment)
:
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Navigation.findNavController(this, R.id.nav_host_fragment).navigate(R.id.galleryFragment);
}
});
Upvotes: 1