简体   繁体   中英

Kotlin Update TextView after Dialog dismiss

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, eg onAttach, onResume, onStart, onViewStateRestored, but none of them start when I close the dialog. How can I do it properly?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM