如何使用导航组件创建 BottomSheetDialogFragment?

48

我正在使用 BottomSheetDialogFragment 显示一些自定义设置。

需求:

当我点击 BottomSheetDialogFragment 中的任何选项卡时,我将替换该片段并将其添加到回退堆栈中,以便在用户单击“返回”或“上一步”操作时,它应返回到 BottomSheetDialogFragment 的最后一个设置片段。

我想使用 Navigation Architecture Component 简化我的事务。

问题: 如果我使用 Navigation Architecture Component 从 FragmentA 导航到 BottomSheetDialogFragment,则会收到以下错误:

java.lang.IllegalStateException: dialog must not be null BottomSheetDialogFragment

我不知道如何使用 Navigation Architecture Component 实例化 BottomSheetDialogFragment,并且使用下面的代码将无法使用 Navigation Architecture Component 维护回退堆栈。

BottomSheetDialogFragment.show(FragmentManager manager, String tag)

你好 @anmol,你解决了这个问题吗?因为我也在尝试做同样的事情。 - Hemant Sangle
我尝试用不同的方式做了一下,看看这个演示项目 https://github.com/andor201995/NavigationDemo @HemantSangle - Anmol
好的,我会检查链接。 - Hemant Sangle
我会构建一个恰当的答案并在这里发布。@HemantSangle - Anmol
那将会很棒。 - Hemant Sangle
1个回答

94
在导航组件版本2.1.0-alpha04中,Navigation Graph可以将dialog作为目的地之一。
<?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"
    app:startDestination="@id/startFragment">

    <fragment
        android:id="@+id/loginFragment"
        android:name="com.awesomeproject.android.authentication.login.LoginFragment"
        android:label="Login"
        tools:layout="@layout/login_fragment" />

    <dialog
        android:id="@+id/bottomSheet"
        android:name="com.awesomproject.android.BottomSheetFragment"
        tools:layout="@layout/bottom_sheet_dialog_fragment" />

</navigation>

BottomSheetFragment将类似于其他底部工作表。

class BottomSheetFragment : BottomSheetDialogFragment() {
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View =
            inflater.inflate(R.layout.bottom_sheet_dialog_fragment, container, false)
}

接下来,您可以像其他目标一样处理bottomSheet。您可以导航到此目标或传递safeArgs

干杯!


4
我尝试过这个,但是当我尝试使用导航从对话框中进行导航时,NavController丢失了。你能分享一下从对话框导航到其他片段或对话框的代码吗?@Boonya - Anmol
3
使用这种解决方案,底部窗格在另一个片段中显示时不会遮挡调用它的当前片段。 - AndroLife
3
加入底部菜单时,当全屏打开时,使用导航功能有点吓人。但你帮我省了时间。将对话框从片段中更改很容易。 - Pranav P
@AndroLife,你知道那个问题的解决方案吗? - Ralph
@AndroLife 顺便说一下,我在使用 Material 1.4.0 和 Navigation 2.3.5 时看到了正确的行为。 - tir38
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接