如何在android中将参数传递给dialog?

如何在android中将参数传递给dialog?,android,kotlin,android-dialogfragment,Android,Kotlin,Android Dialogfragment,我正在调用一个包含以下参数的对话框: MyDialog("title", "message").show(this@MyActivity.supportFragmentManager, null) 这是我的对话课: class MyDialog(private val theTitle: String, private val theMessage: String) : DialogFragment() { override fun onCreateDialog(savedInstan

我正在调用一个包含以下参数的对话框:

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()
        }
    }
}
但当设备旋转方向改变时,应用程序停止工作。 如果不传递任何参数,则不会发生这种情况。
那么,如何传递参数以及最好的方法是什么呢?

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

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()
        }
    }
}
您可以这样调用您的对话框:

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

对于任何片段,请始终记住使用参数传递数据

尝试以下代码并将任何数据作为参数传递,因为我传递了一条消息

    private void confirmdialog(String msg_str) {

    final Dialog dialog = new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setCancelable(false);
    dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
    LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v1 = li.inflate(R.layout.dialog_forsurity, null, false);
    dialog.setContentView(v1);
    dialog.setCancelable(true);


    TextView msg = (TextView) v1.findViewById(R.id.msg);
    msg.setText(msg_str);

    Button btn_submit = (Button) v1.findViewById(R.id.btn_submit);


    btn_submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            dialog.dismiss();

            Intent intent = new Intent(SellNumberPlateActivity.this, HomeActivity.class);
            startActivity(intent);
            finishAffinity();

        }
    });

    dialog.show();
    Window window = dialog.getWindow();
    window.setLayout(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

}
这里R.layout.dialog\u forsurity是您的对话框设计

您应该通过bundle传递参数的原因是,当系统恢复一个片段(例如在配置更改时)时,它将自动恢复您的bundle

资料来源:

不要创建DialogFragment-您应该通过从其类调用静态方法来实例化:

public static MyDialog newInstance(String param1) {
    MyDialog d = new MyDialog ();

    Bundle args = new Bundle();
    args.putString("param1", param1);
    d.setArguments(args);

    return d;
}
当你想展示它时,你可以打电话:

MyDialog dialog = MyDialog .newInstance("lorem ipsum");
dialog.show(fm, "fragment_confirm_dialog");

来源:

使用kotlin的完整解决方案

第1步。像下面这样创建类

class MyDialog : DialogFragment() {

    private var title: String? = null
    private var message: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            title = it.getString(ARG_TITLE)
            message = it.getString(ARG_MESSAGE)
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return activity.let {
            val myBuilder = AlertDialog.Builder(it)
                myBuilder
                    .setTitle(title)
                    .setMessage(message)
                    .setPositiveButton("OK") { _, _ -> }
            myBuilder.create()
        }
    }

    companion object {
        const val TAG = "myDialog"
        private const val ARG_TITLE = "argTitle"
        private const val ARG_MESSAGE = "argMessage"

        fun newInstance(title: String, message: String) = MyDialog().apply {
            arguments = Bundle().apply {
                putString(ARG_TITLE, title)
                putString(ARG_MESSAGE, message)
            }
        }
    }
}
步骤2。创建实例并显示它

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

就这些

如果应用程序停止..堆栈跟踪应该是有用的,这在问题中没有提到。您是否查阅了日志。我认为问题有所不同。如果您使用的是
AlertDialog.Builder
,我认为您可以避免使用
DialogFragment
,而只使用
AlertDialog
。这有帮助吗<代码>原因:androidx.fragment.app.fragment$InstantiationException:无法实例化fragment com.example.kotlinapp2.DialogPicker:找不到片段构造函数MyDialog实际上是DialogPickerI我想让
MyDialog
更复杂,所以我想我不能只使用
AlertDialog
我已经更新了答案。一切正常。唯一的区别是在参数中传递数据,而不是constructor@AbnerEscócio在访问bundle.contains(“KEY1”)之前,您应该始终检查bundle是否包含特定的密钥我没有得到它,假设我在一个bundle中添加一些
KEY1
,对话框可以工作,然后我调用另一个带有
KEY1
的对话框,但是使用不同的值,新对话框仍然可以工作,但是bundle不是已经包含该键了吗?@user8455110我不理解这个场景。请使用PSEDOO代码进行更新。