如何将参数传递给 dialogFragment

How to pass an argument to dialogFragment

如何将值传递给对话框片段?

假设我有 isStarted 布尔值,我将此参数传递给 DialogFragment,如下所示:

DatePickerFragmentDialog(isStarted).show

在我的 DialogFragment 里面我得到了论点:

class DatePickerFragmentDialog(isStarted: Boolean) : DialogFragment() {

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {}
}

但是我不能在 onCreateDialog 覆盖方法中使用这个 argumnet

您需要使用参数来传递您的值:

class DatePickerFragmentDialog : DialogFragment() {

    companion object {
        fun newInstance(isStarted: Boolean): DatePickerFragmentDialog {
            val f = DatePickerFragmentDialog()
            // Supply isStarted input as an argument.
            val args = Bundle()
            args.putBoolean("isStarted", isStarted)
            f.arguments = args
            return f
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val isStarted = arguments?.getBoolean("isStarted")
        // Return some dialog
        return super.onCreateDialog(savedInstanceState)
    }
}

显示它:

val fragment = DatePickerFragmentDialog.newInstance(true)
fragment.show(supportFragmentManager, "myFragment")