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

Anm*_*mol 10 android bottom-sheet android-architecture-components android-architecture-navigation

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

需求:

当我单击BottomSheetDialogFragment中的任何选项卡时,我会替换该片段并将其添加到Backstack中,以便当用户单击onBackPress或Up操作时,它应返回BottomSheetDialogFragment的最后一个设置的片段。

我想使用导航体系结构组件来简化我的交易。

问题:如果我使用导航体系结构组件从FragmentA导航到BottomSheetDialogFragment,那么我会收到以下错误。

java.lang.IllegalStateException:对话框不能为空BottomSheetDialogFragment

我不知道如何使用导航体系结构组件实例化BottomSheetDialogFragment,并且使用下面的代码将不会使用导航体系结构组件进行维护。

BottomSheetDialogFragment.show(FragmentManager manager, String tag)
Run Code Online (Sandbox Code Playgroud)

Boo*_*tak 9

在导航组件版本中2.1.0-alpha04Navigation 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>
Run Code Online (Sandbox Code Playgroud)

BottomSheetFragment看起来与其他BottomSheet相似。

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

然后,您可以像对待bottomSheet其他目的地一样对待。您可以导航到该目的地或传递safeArgs

干杯!

  • 我试过了,但是当我尝试使用导航从对话框导航时,缺少 NavController 您可以共享从对话框到其他片段或对话框的导航代码吗?@Boonya (3认同)
  • 使用此解决方案,底部工作表显示在另一个片段中,不会遮蔽调用它的当前片段 (2认同)
  • 天哪,当我在全屏打开 BottomSheet 时添加带有导航的时候,真是太可怕了。但你节省了我的时间。从片段中更改对话框很容易。 (2认同)