为什么此代码不起作用?使用Kotlin显示对话框

问题描述 投票:0回答:4

单击浮动动作按钮时,我想创建一个对话框窗口。但是,当我单击按钮时,仅显示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时显示对话框窗口?

android kotlin dialog floating-action-button
4个回答
0
投票

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


0
投票

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


0
投票

您必须像以下那样调用show()

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

//show alert dialog.
dialog.show();

0
投票

创建对话框后,我们需要调用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()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.