如何在android中将参数传递给对话框? [英] How to pass arguments to dialog in android?

查看:51
本文介绍了如何在android中将参数传递给对话框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调用一个带有如下参数的对话框:

I am calling a dialog with arguments as follows:

MyDialog("title", "message").show(this@MyActivity.supportFragmentManager, null)

这是我的对话类:

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?

推荐答案

如果它是一个片段,那么应该总是有一个可用的默认构造函数.单独传递参数将确保参数在片段的状态变化中保持不变
所以有一个方法 setArgument(Bundle) 您可以在其中传递参数.所以这里你的电话应该改写为

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()
        }
    }
}

你这样称呼你 Dialog:

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

这篇关于如何在android中将参数传递给对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆