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

标签 android android-architecture-components bottom-sheet android-architecture-navigation

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

要求:

当我单击 BottomSheetDialogFragment 中的任何选项卡时,我会替换该 fragment 并将其添加到后台堆栈,这样当用户单击 onBackPress 或 Up 操作时,它应该返回上次设置的 BottomSheetDialogFragment fragment 。

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

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

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

我不知道如何使用导航架构组件实例化 BottomSheetDialogFragment,并且使用下面的代码不会有使用导航架构组件的维护后台堆栈。

BottomSheetDialogFragment.show(FragmentManager manager, String tag)

最佳答案

在导航组件版本 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 看起来与其他 BottomSheet 相似。

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 传入。

干杯!

关于android - 如何使用导航架构组件创建 BottomSheetDialogFragment?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53431473/

相关文章:

android - 如何始终在 Bottom Sheet 对话框 fragment 中将按钮与屏幕底部对齐

android - 无法解析 : multidex-instrumentation

android-recyclerview - PagedListAdapter在接收到新的PagedList时跳到列表的开头

android - 不同屏幕尺寸的动态 View

android - RoomDatabase_Impl 不存在

安卓房间。哪种插入方法会更快?

android - AppBarLayout 阻止 RecyclerView 在 BottomSheet 中滚动

android - 如何将数据从 BottomSheetDialogFragment 返回到父 Fragment

android - 使用 getLoader 结果同步单元测试异步任务加载器

android - 使用 Facebook sdk 3.1 将链接发布到 Facebook 页面墙