Android Pass Argument/Data to DialogFragment

and Pass Result from DialogFragment to Activity
class LocationPickerDialog : DialogFragment() {    companion object {        private const val EXTRA_LAT = "lat"        private const val EXTRA_LNG = "lng"        fun newInstance(lat: Double? = null, lng: Double? = null): LocationPickerDialog {            val dialog = LocationPickerDialog()            val args = Bundle().apply {                lat?.let { putDouble(EXTRA_LAT, it) }                lng?.let { putDouble(EXTRA_LNG, it) }            }            dialog.arguments = args            return dialog        }    }    var onResult: ((lat: Double, lng: Double) -> Unit)? = null    override fun onActivityCreated(savedInstanceState: Bundle?) {        super.onActivityCreated(savedInstanceState)        // receive arguments        val lat = arguments?.getDouble(EXTRA_LAT)        val lng = arguments?.getDouble(EXTRA_LNG)           // return result        onResult?.invoke(lat, lng)    }}

Launch DialogFragment from Activity, passing arguments and receiving result.

val dialog = LocationPickerDialog.newInstance(lat, lng)dialog.onResult = { lat, lng ->    // do something}dialog.show(supportFragmentManager, "editLocation")

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.