Safal Kumar Ghimire
Safal Kumar Ghimire

Reputation: 318

How to make a callback to the original parent fragment from the second child fragment?

I currently have the ParentFragment which is opening a ActionSheetFragment and onClick of button from ActionSheetFragment opens another fragment ValidationFragment dismissing the current one.

I want to refresh the contents of the ParentFragment when the ValidationFragment is dismissed. The onResume method of the ParentFragment is not called.

I tried using the callbacks but its only working for two fragments.

I also tried the setFragment and getFragment methods. None of them are working because I have the fragment in middle i.e ActionSheetFragment which is dismissed after opening the ValidationFragment. Can anybody help me solve this?

Upvotes: 1

Views: 275

Answers (1)

Sijan Gurung
Sijan Gurung

Reputation: 797

when calling the ActionSheetFragment from ParentFragment, set the parentFragment as targetFragment

 val actiondialog = ActionSheetFragment.getInstance()
 actiondialog.setTargetFragment(this, 119)
 actiondialog.show(this.fragmentManager, "ActionSheetFragment")

and when the ValidationFragment is being called from ActionSheetFragment, just forward the targetFragment to ValidationFragment like:

val validationFragment = ValidationFragment.getInstance()
validationFragment.setTargetFragment(targetFragment, 119)
validationFragment.show(this.fragmentManager, "ValidationFragment")
[email protected]()

So, in ParentFragment, you get the activityResult with the same code,

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    when (requestCode) {
        119 ->
            if (resultCode == Activity.RESULT_OK) {
                // DO YOUR REFRESHING CODE HERE.
            }
    }
}

Upvotes: 1

Related Questions