For all Kotlin developers:
Here is the solution Android Studio offers to send data to your fragment (= when you create an empty fragment using a file โ New โ Fragment โ Fragment (empty) and you mark โenable fragment factoryโ โ).
Put this in your snippet:
class MyFragment: Fragment { ... companion object { @JvmStatic fun newInstance(isMyBoolean: Boolean) = MyFragment().apply { arguments = Bundle().apply { putBoolean("REPLACE WITH A STRING CONSTANT", isMyBoolean) } } } }
.apply is a good technique for setting data when creating an object, or as they claim here :
Calls the specified function [block] with the value of this as the receiver and returns the value of this .
Then in your activity or fragment do:
val fragment = MyFragment.newInstance(false) ...
and read the Arguments in your snippet, such as:
private var isMyBoolean = false override fun onAttach(context: Context?) { super.onAttach(context) arguments?.getBoolean("REPLACE WITH A STRING CONSTANT")?.let { isMyBoolean = it } }
To "send" data back to your activity , simply define the function in your activity and follow these steps in your fragment:
(activity as? YourActivityClass)?.callYourFunctionLikeThis(date) // your function will not be called if your Activity is null or is a different Class
Enjoy the magic of Kotlin!
Spipau Sep 23 '19 at 11:03 2019-09-23 11:03
source share