【问题标题】:Pass data from Bottom Sheet Dialog Fragment to Fragment将数据从底部工作表对话框片段传递到片段
【发布时间】:2025-12-15 23:10:01
【问题描述】:

我正在使用带有导航架构组件的 BottomSheetDialogFragment 类。我遵循单一活动模式,因此我只有一个活动和几个片段。下面是我的代码。

BottomSheetDialogFragment.kt

class LogoBottomSheetFragment : BottomSheetDialogFragment() {

private var _binding: FragmentBottomSheetAccountLogoBinding? = null
private val binding get() = _binding!!

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    _binding = FragmentBottomSheetAccountLogoBinding.inflate(inflater, container, false)

    return binding.root
}

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}
}

这就是我如何从我的主要片段中打开我的 navigation.xml 中的对话框:

    <dialog
    android:id="@+id/logoBottomSheetFragment"
    android:name="com.th3pl4gu3.locky.ui.main.add.account.LogoBottomSheetFragment"
    android:label="LogoBottomSheetFragment"
    tools:layout="@layout/fragment_bottom_sheet_account_logo" />

现在我想将底部工作表中的数据传递到主要片段。

有没有合适的方法来做到这一点?谁能帮帮我。

谢谢。

【问题讨论】:

标签: android kotlin android-architecture-navigation android-bottomsheetdialog


【解决方案1】:

Navigation 2.3.0-alpha02 开始,Navigation 已内置支持 Returning a result 到以前的目的地。

这分为两部分,您的第一个片段(想要接收结果的片段)将使用navController.currentBackStackEntry?.savedStateHandle 来获取对与其在导航控制器中的NavBackStackEntry 关联的SavedStateHandle 的引用。然后,它可以observe 一个特定的键在该键更改时获取回调。

第二个片段(传递结果的片段,即您的LogoBottomSheetFragment)将通过使用navController.previousBackStackEntry?.savedStateHandle 获得对完全相同的SavedStateHandle 的引用。当第二个片段在SavedStateHandle 上调用set 时,该结果可用于第一个片段。

请注意,有一些DialogFragment specific considerations 需要牢记——因为前一个片段是RESUMED,即使在显示BottomSheetFragment 时,结果也会立即发送到您的第一个片段。

【讨论】: