Refresh fragment when dialogfragment is dismissed

前端 未结 6 1849
南方客
南方客 2021-02-04 01:01

Is there any way I can detect when a DialogFragment is dismissed, so that i can update its parent fragment?

6条回答
  •  [愿得一人]
    2021-02-04 01:57

    The top rated answers here have issues.

    You cannot hold listeners as instance variables in a DialogFragment, as they will not survive recreation, and you will left wondering why your callbacks 'magically' stop working.

    You can read more about this here:

    https://medium.com/@lukeneedham/listeners-in-dialogfragments-be636bd7f480

    This article offers a couple of real solutions, of which my favourite is to use targetFragment with a custom interface. For intercepting the dismiss, that looks like:

    class MainFragment : Fragment(R.layout.fragment_main), DummyDialogCallback {
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            openDialogButton.setOnClickListener {
                val dialog = DummyDialog()
                dialog.setTargetFragment(this, DIALOG_DUMMY)
                dialog.show(requireFragmentManager(), "DummyDialog")
            }
        }
    
        override fun onDummyDialogClick() {
            Toast.makeText(requireContext(), "Dummy click", Toast.LENGTH_SHORT).show()
        }
    
        companion object {
            const val DIALOG_DUMMY = 1
        }
    }
    
    class DummyDialog : DialogFragment() {
        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ) = inflater.inflate(R.layout.dialog_dummy, container, false)
    
        override fun onDismiss(dialog: DialogInterface) {
            super.onDismiss(dialog)
            val callback = targetFragment as? DummyDialogCallback
            callback?.onDummyDialogClick()
        }
    }
    
    interface DummyDialogCallback {
        fun onDummyDialogClick()
    }
    

提交回复
热议问题