为什么 Dialog 在 Kotlin 中不显示?

why Dialog doesn't show in Kotlin?

我想在单击浮动操作按钮时创建一个对话框 window。但是,当我单击按钮时,只会出现 Toast 消息。

这是我目前尝试过的方法:

    recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
    val users = ArrayList<User>()

    users.add(User("John", "USA"))

    val adapter = CustomAdapter(users)

    recyclerView.adapter = adapter

    fab.setOnClickListener {
        val dialog = Dialog(this)
        Toast.makeText(this, "It's working...", Toast.LENGTH_LONG).show()
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setContentView(R.layout.dialog_add)
        dialog.setTitle("Add person")
        dialog.setCancelable(false)

        val nameText = dialog.findViewById(R.id.name) as EditText
        val addressText = dialog.findViewById(R.id.address) as EditText
        val btnAdd = dialog.findViewById(R.id.btn_ok) as Button
        val btnCancel = dialog.findViewById(R.id.btn_cancel) as Button

        btnAdd.setOnClickListener{
            users.add(User(nameText.text.toString(), addressText.text.toString()))
            adapter.notifyDataSetChanged()
            dialog.dismiss()
        }
        btnCancel.setOnClickListener {
            dialog.dismiss()
        }
    }
}

如何更改代码,以便在单击 FAB 时显示对话框 Window?

更新: 你们是对的!在我输入 dialog.show() 后它工作得很好。谢谢。

您忘记在对话框中调用 show() 。 dialog.show()

您需要调用 dialog.show()。只需在 dialog.setCancelable(false) 以下的任何位置调用它。

您必须像下面这样调用 show()

//...
dialog.setTitle("Add person")
dialog.setCancelable(false)
// ...
btnAdd.setOnClickListener{
    //...
}
btnCancel.setOnClickListener {
    dialog.dismiss()
}

//show dialog adding below line.
dialog.show();

创建对话框后,我们需要调用show方法在屏幕上显示对话框

在创建对话框后添加这一行dialog.show()

请替换或添加此代码

recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
    val users = ArrayList<User>()

    users.add(User("John", "USA"))

    val adapter = CustomAdapter(users)

    recyclerView.adapter = adapter

    fab.setOnClickListener {
        val dialog = Dialog(this)
        Toast.makeText(this, "It's working...", Toast.LENGTH_LONG).show()
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setContentView(R.layout.dialog_add)
        dialog.setTitle("Add person")
        dialog.setCancelable(false)

        val nameText = dialog.findViewById(R.id.name) as EditText
        val addressText = dialog.findViewById(R.id.address) as EditText
        val btnAdd = dialog.findViewById(R.id.btn_ok) as Button
        val btnCancel = dialog.findViewById(R.id.btn_cancel) as Button

        btnAdd.setOnClickListener{
            users.add(User(nameText.text.toString(), addressText.text.toString()))
            adapter.notifyDataSetChanged()
            dialog.dismiss()
        }
        btnCancel.setOnClickListener {
            dialog.dismiss()
        }
    //add this line 
     //Call show() method to show dialog 
  dialog.show()
    }
}