如何使用导航喷气背包在另一个片段之上添加片段?
How to add fragment on top of another fragment using navigation jetpack?
我想在另一个片段之上添加一个片段。但是在使用navigation jetpack时,好像是替换了fragment而不是adding。
其实我想显示一个弹出页面,这样两个片段就可以相互通信,这似乎适用于旧的添加片段功能,但最近我们的项目被替换为导航jetpack。
其中一个选项是让您的第二个片段扩展 DialogFragment
并将其作为 <dialog>
而不是 <fragment>
添加到您的导航图中。它将被导航组件自动显示为对话。
这是一个例子:
<dialog
android:id="@+id/myPopupDialogFragment"
android:name="project.package.name.MyDialogFragment"
android:label="MyDialogFragment">
<!-- add arguments if you wish -->
</dialog>
您可以使用全屏主题或底部 sheet 使用以下方法使此对话全屏显示:
Theme.MaterialComponents.Light.BottomSheetDialog
这对我有用 ->
fun ShowDialog()
{
//Inflate the dialog with custom view
val mDialogView =
LayoutInflater.from(context).inflate(R.layout.layout_popup, null)
//AlertDialogBuilder
val mBuilder = AlertDialog.Builder(context)
.setView(mDialogView)
//show dialog
val alertDialog=mBuilder.show()
mDialogView.button_close.setOnClickListener {
alertDialog.dismiss()
}
mDialogView.button_submit.setOnClickListener {
viewModel.data.value="Data"
alertDialog.dismiss()
}
}
因此,我们可以添加一个对话框并向视图添加一个侦听器,而不是添加片段并与之通信。
我想在另一个片段之上添加一个片段。但是在使用navigation jetpack时,好像是替换了fragment而不是adding。
其实我想显示一个弹出页面,这样两个片段就可以相互通信,这似乎适用于旧的添加片段功能,但最近我们的项目被替换为导航jetpack。
其中一个选项是让您的第二个片段扩展 DialogFragment
并将其作为 <dialog>
而不是 <fragment>
添加到您的导航图中。它将被导航组件自动显示为对话。
这是一个例子:
<dialog
android:id="@+id/myPopupDialogFragment"
android:name="project.package.name.MyDialogFragment"
android:label="MyDialogFragment">
<!-- add arguments if you wish -->
</dialog>
您可以使用全屏主题或底部 sheet 使用以下方法使此对话全屏显示:
Theme.MaterialComponents.Light.BottomSheetDialog
这对我有用 ->
fun ShowDialog()
{
//Inflate the dialog with custom view
val mDialogView =
LayoutInflater.from(context).inflate(R.layout.layout_popup, null)
//AlertDialogBuilder
val mBuilder = AlertDialog.Builder(context)
.setView(mDialogView)
//show dialog
val alertDialog=mBuilder.show()
mDialogView.button_close.setOnClickListener {
alertDialog.dismiss()
}
mDialogView.button_submit.setOnClickListener {
viewModel.data.value="Data"
alertDialog.dismiss()
}
}
因此,我们可以添加一个对话框并向视图添加一个侦听器,而不是添加片段并与之通信。