【问题标题】:How can the fragment know that the dialog is closed?片段如何知道对话框已关闭?
【发布时间】:2023-03-15 20:00:01
【问题描述】:

我想在bottom navigationfragment 中通过button 打开dialog fragment,并在对话框结束时将此按钮设为INVISIBLE

为了制作按钮INVISIBLE,我想我需要处理打开对话框的片段,而不是对话框片段,但我不知道如何。

我如何从片段中知道对话正在结束

【问题讨论】:

标签: android kotlin android-fragments android-dialogfragment


【解决方案1】:

试试下面的代码。

//Receiver class
class CustomResultReceiver(handler: Handler?, receiver: 
ResultReceiverCallBack) :
ResultReceiver(handler), Serializable {
private var mReceiver: ResultReceiverCallBack = receiver

override fun onReceiveResult(resultCode: Int, resultData: Bundle) 
{
mReceiver?.onDialogCancel(true, resultCode, resultData)
}

interface ResultReceiverCallBack {
fun onDialogCancel(action: Boolean, resultCode: Int, resultData: 
 Bundle)
}

}


//Fragment A
Class 
FragmentA:Fragment(),CustomResultReceiver.ResultReceiverCallBack 
{
private lateinit var binding: FragmentABinding

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentABinding.inflate(inflater, container, false)
return binding.root
}

override fun onViewCreated(view: View, savedInstanceState: 
 Bundle?) {
 super.onViewCreated(view, savedInstanceState)

 binding.dialogButton.setOnClickListener{
 findNavController().navigate(
 R.id.action_FragmentA_to_FragmentB,
 Bundle().apply { putSerializable("key", 
 CustomResultReceiver(Handler(requireContext().mainLooper), 
  this@FragmentA))})
 }
 }

 override fun onDialogCancel(action: Boolean, resultCode: Int, 
 resultData: 
 Bundle) {
 toast(“Dialog cancel“)
}
} 


//Fragment B as Dialog fragment
Class FragmentB:DialogFragment(){
private lateinit var binding: FragmentBBinding
private var resultReceiver: ResultReceiver? = null

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentBBinding.inflate(inflater, container, false)
return binding.root
}

 override fun onViewCreated(view: View, savedInstanceState: 
 Bundle?) {
 super.onViewCreated(view, savedInstanceState)
  arguments.let {
  resultReceiver = arguments?.getSerializable("key") as 
  CustomResultReceiver
  }

 }
override fun onCancel(dialog: DialogInterface) {
super.onCancel(dialog)
resultReceiver.onDialogCancel()
}
}

【讨论】:

  • 感谢您的回复。虽然忘记了也没有在正文中提及,但我也是用Navigation Componentfragment A启动dialog fragment B。通过使用nav_graph。所以我不能使用回调函数来创建一个像你的代码一样的对话框..
  • 我也使用导航图更新了代码
猜你喜欢
  • 1970-01-01
  • 2022-01-09
  • 2018-03-04
  • 2015-04-17
  • 1970-01-01
  • 2014-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多