我正在使用导航组件,它可以在片段之间导航,并且显示了操作栏中的向上箭头,但发生了一个问题,导致后退按钮也不起作用,向上箭头按钮也不起作用。
我在绑定元素的主要活动中的代码:
@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);
}
我的主要导航图代码是:
<?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"
/>
我的主要活动xml文件:
<?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" />
我通过观察片段中的 LiveDate<Void>
对象导航到第二个片段,如下所示:
viewModel.cardClicks.observe(getViewLifecycleOwner(),
__ -> NavHostFragment.findNavController(this).navigate(R.id.action_mainFragment_to_employeesFragment));