Search code examples
androidkotlinandroid-dialogfragment

How to pass arguments to dialog in android?


I am calling a dialog with arguments as follows:

MyDialog("title", "message").show([email protected], null)

And this is my dialog class:

class MyDialog(private val theTitle: String, private val theMessage: String) : DialogFragment() {
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return activity.let {
            val myBuilder = AlertDialog.Builder(it)
            myBuilder
                .setTitle(theTitle)
                .setMessage(theMessage)
                .setPositiveButton("OK") { _, _ -> }
            myBuilder.create()
        }
    }
}

But when the orientation of device changes on rotation, the app stops working. That doesn't happen if no arguments are passed. So, how to pass arguments and what is the best way to do so?


Solution

  • If its a fragment, then there should be always a default constructor available. Passing arguments separate will ensure that the arguments are preserved across state changes of the fragment
    So there is a method setArgument(Bundle) in which you can pass your parameters. So here your call should be rewritten as

    class MyDialog: DialogFragment() {
        override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
            return activity.let {
                 val arg = arguments
                // Use the parameters by accessing the key from variable "arg"
                val myBuilder = AlertDialog.Builder(it)
                myBuilder
                    .setTitle(theTitle)
                    .setMessage(theMessage)
                    .setPositiveButton("OK") { _, _ -> }
                myBuilder.create()
            }
        }
    }
    

    You call you Dialog like this:

    val d = MyDialog()
    val b = Bundle()
    b.putInt("KEY1",1)
    d.arguments = b
    d.show(FragmentManager,Tag)
    

    For any fragment always remember to use arguments to pass data