I have a dialog with a button. I want to change a TextView (txtTotalDist) in the parent fragment when the button is clicked and the dialog is closed.
I tried several methods without success:
rootView.btnDialogOK.setOnClickListener {
val frag: ParentFragment()
frag.txtTotalDist.text="A"
//Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
(activity as ParentFragment).txtTotalDist.post { txtTotalDist.text = "A" }
//cannot be cast to ParentFragment
txtTotalDist.post { txtTotalDist.text = "A" }
//Attempt to invoke virtual method 'boolean android.widget.TextView.post(java.lang.Runnable)' on a null object reference
txtTotalDist.text = "A"
//Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
dismiss()
}
I also tried to find a function in the parent fragment to override, e.g. onAttach, onResume, onStart, onViewStateRestored, but none of them start when I close the dialog. How can I do it properly?
EDIT / SOLUTION
build.gradle Module:
implementation 'androidx.fragment:fragment-ktx:1.4.0'
Host fragment:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setFragmentResultListener("requestKey") { key, bundle ->
val result = bundle.getString("action")
if (result=="del") refreshStatusBar()
}
}
Dialog fragment:
rootView.btnDialogRemove.setOnClickListener {
setFragmentResult("requestKey", bundleOf("action" to "del"))
dismiss()
}
CodePudding user response:
If the second fragment is nested inside in first fragment, you can pass a callback to second fragment and invoke it after closing dialog, or you can return an observable from second fragment to observe by first one. But if your designed fragments are sibling with each other, it depends on your designed code base. If you are using fragment manager directly, you can do the same approach as above and add second fragment instead of replacing it. But if you have to replace or you are using navigation component, there is a better way to handle it like we do between two activities. You can add below code lines to first fragment:
setResultListener("yourKey") { key, Any ->
val result = anything you need to return
//Todo something about result
}
And in second activity when you want to set data after closing dialog or whenever:
val result = any result
setResult("yourKey",result)
Also you can check the below url for more information about it. https://developer.android.com/training/basics/fragments/pass-data-between#kotlin