Home > Enterprise >  How to notice when DialogFragment is dismissed in my Fragment?
How to notice when DialogFragment is dismissed in my Fragment?

Time:10-05

I'm navigating from a Fragment to a DialogFragment. What I want to do is notice when this DialogFragment is dismissed in my Fragment to do something.

I'm trying doing this updating a LiveData but for some reason,when the DialogFragment is closed, the LiveData value is never true like I'm trying to do.

MyFragment:

private val myViewModel: MyViewModel by viewModel() //Using Koin
btn1.setOnClickListener{
   findNavController().navigate(R.id.my_dialog_fragment)
}

myViewModel.dialogFragmentIsClosed.observe(viewLifecycleOwner){isClosed->
if(isClosed)
  //do something
}

MyViewModel:

private val _dialogFragmentIsClosed = MutableLiveData(false)
val dialogFragmentIsClosed: LiveData<Boolean> get() = _dialogFragmentIsClosed
fun isDialogFragmentClosed(closed:Boolean){
  _dialogFragmentIsClosed.postValue(closed)
}

DialogFragment:

private val myViewModel: MyViewModel by viewModel() //Using Koin

override fun onDismiss(dialog:DialogInterface){
  myViewModel.isDialogFragmentClosed(true)
  val bundle = bundleOf(Pair("argBoolean",true))
  findNavController().navigate(R.id.my_fragment,bundle)
}

CodePudding user response:

First of all, your DialogFragment and MyFragment are not sharing the same instance of MyViewModel.

To achieve your goal, you should check this document: https://developer.android.com/guide/navigation/navigation-programmatic#additional_considerations

You will open DialogFragment from MyFragment, then observer the result from DialogFragment.

If you want to share the same instance of ViewModel, change to use activityViewModel() ( instead of using viewModel() )

CodePudding user response:

You could use a interface to listen dismiss event. This is a simple way

First, create interface and put it in your dialog fragment:

interface CloseListener {
    fun onClose()
}
class YourDialog(private val listener: CloseListener) : DialogFragment() {
   override fun onDismiss(dialog:DialogInterface){
      listener.onClose()
   }
}

And then, in your fragment, calling dialogfragment like this:

val yourDialog = YourDialog(object: CloseListener{
   override fun onClose() {
       //do something here, such as set value for your viewModel
   }
})
yourDialog.show(childFragmentManager, null)

Hope it can help you

  • Related