I have created the default Android Studio Navigation Drawer project. By default, I have one activity and three main fragments. (Home, Gallery, Slideshow), I am only trying with the Home Fragment. I have replaced the < fragment > from the content_main XML to
<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment_content_main"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/mobile_navigation" />
and Modified the MainActivity as
//inside onCreate
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment_content_main);
NavController navController;
if (navHostFragment != null) {
navController = navHostFragment.getNavController();
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
} else {
Log.e("Error", "Failed on NULL NavController");
}
//and modified the following
@Override
public boolean onSupportNavigateUp() {
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment_content_main);
assert navHostFragment != null;
return NavigationUI.navigateUp(navHostFragment.getNavController(), mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
Next, I have created one BlankFragment. On the home Fragment, I have a button and onClickListener to replace the HomeFragment with BlankFragment as
binding.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("onClick: ", "Clicked");
BlankFragment blankFragment = new BlankFragment();
requireActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment_content_main, blankFragment, null)
.addToBackStack("blank").commit();
}
});
Now after clicking on the button the fragment is replaced with the blank fragment but from there if I try to open the Navigation drawer I get the following Error for the first line of the above onSupportNavigateUp() function :
java.lang.ClassCastException: BlankFragment cannot be cast to androidx.navigation.fragment.NavHostFragment
How to solve this. Thanks in Advance.
As suggested by Zain in the comment, I tried using navController. Tried the following and it seems to work, posting for others. https://learntodroid.com/how-to-move-between-fragments-using-the-navigation-component/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.