![](/img/trans.png)
[英]Why Android Navigation Component screen not go back to previous Fragment,but a method in onViewCreated of previos Fragment being called?
[英]Why I cannot go back to previous fragment with Navigation Component?
在我的應用程序中,我有 3 個主屏幕 - 探索、我的群組、個人資料。 在我的組中,我有組列表,當我單擊一個組時,我被重定向執行單個 GroupFragment。 那工作很好。 但是當我想通過手勢(從手機右側到中心)返回時,應用程序將進入后台並顯示“桌面”。 我想將 go 從組返回到 MyGroups 片段。
編輯:我可以 go 回到上一個片段(MyGroups)的唯一方法是在組片段中的某個按鈕上創建 onClickListener。 像那樣:
backButton.setOnClickListener { findNavController().popBackStack() }
為什么我下面的代碼無法正常使用手勢向后滑動?
導航儀表板菜單:
<?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"
android:id="@+id/nav_dashboard_menu"
app:startDestination="@id/nav_explore">
<include app:graph="@navigation/nav_explore" />
<include app:graph="@navigation/nav_my_groups" />
<include app:graph="@navigation/nav_profile" />
</navigation>
nav_my_groups:
<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/nav_my_groups"
app:startDestination="@id/myGroupsFragment">
<include app:graph="@navigation/nav_group" />
<fragment
android:id="@+id/myGroupsFragment"
android:name="com.wojciechkula.locals.presentation.mygroups.MyGroupsFragment"
android:label="My groups"
tools:layout="@layout/fragment_my_groups">
<action
android:id="@+id/openGroup"
app:destination="@id/nav_group">
<argument
android:name="groupId"
app:argType="string" />
<argument
android:name="groupName"
app:argType="string" />
</action>
</fragment>
</navigation>
導航組:
<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/nav_group"
app:startDestination="@id/groupFragment">
<fragment
android:id="@+id/groupFragment"
android:name="com.wojciechkula.locals.presentation.group.GroupFragment"
android:label="Group"
tools:layout="@layout/fragment_group">
<argument
android:name="groupId"
app:argType="string" />
<argument
android:name="groupName"
app:argType="string" />
</fragment>
</navigation>
我將從 MyGroups 轉到帶有 navController 和 Destination 的組。 MyGroupsNavigator:
internal class MyGroupsNavigator @Inject constructor() {
fun openGroup(navController: NavController, id: String, name: String) {
val destination = MyGroupsFragmentDirections.openGroup(id, name)
navController.navigate(destination)
}
}
您也可以使用 OnBackPressDispatcher。 但不要忘記刪除 handleOnBackPress 方法中的回調。 這里
在 OnViewCreated 中:
requireActivity().onBackPressedDispatcher
.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
findNavController().popBackStack()
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.