I'm using navigation component and it works to navigate between fragments and the up arrow in the actionbar is shown but a problem occurred that makes the back button is not working also, the up arrow button is not working.
My code in main activity that binds the elements:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DataBindingUtil.setContentView(this, R.layout.activity_main);
NavHostFragment navHostFragment = (NavHostFragment) (getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment));
assert navHostFragment != null;
NavController navController = navHostFragment.getNavController();
NavigationUI.setupActionBarWithNavController(this, navController);
}
My main navigation graph code is:
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_navigation_graph"
app:startDestination="@id/mainFragment">
<fragment
android:id="@+id/mainFragment"
android:name="com.example.jobfinder.screens.fragments.MainFragment"
android:label="@string/main_fragment_title"
tools:layout="@layout/fragment_main"
>
<action
android:id="@+id/action_mainFragment_to_employeesFragment"
app:destination="@id/employeesFragment" />
</fragment>
<fragment
android:id="@+id/employeesFragment"
android:name="com.example.jobfinder.screens.fragments.EmployeesFragment"
android:label="@string/employees_fragment_title"
tools:layout="@layout/fragment_employees"
/>
My main activitiy xml file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/main_navigation_graph" />
I navigate to the second fragment by observing a LiveDate<Void>
object from the fragment like this:
viewModel.cardClicks.observe(getViewLifecycleOwner(),
__ -> NavHostFragment.findNavController(this).navigate(R.id.action_mainFragment_to_employeesFragment));