Android Pass Argument/Data to DialogFragment

July 24, 2018
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")
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.