1

我有一个按钮,当我单击它时,它应该显示警报对话框,但是当我单击该按钮时应用程序崩溃我知道代码流程是这样的,但我不知道我在哪里做错了

      private lateinit var btn: Button
      
 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_dynam)
        btn = findViewById(R.id.add1)
        buildDialog()

        btn.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
              dialog.show()
            }
        })
    }

    private fun buildDialog() {
        val builder=android.app.AlertDialog.Builder(this)
        val view=layoutInflater.inflate(R.layout.dialog_dynam,null)
      val name=  view.findViewById<EditText>(R.id.nameEdit)
        builder.setView(view)
        builder.setTitle("Enter name")
            .setPositiveButton("Ok",object :DialogInterface.OnClickListener{
                override fun onClick(dialog: DialogInterface?, p1: Int) {
addname(name.text.toString())

                }`
4

1 回答 1

1

我认为你有dialog一个变量,你忘了在函数lateinit中分配它。buildDialog

      private lateinit var btn: Button
      private lateinit var dialog:AlertDialog

      
      override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_dynam)
        btn = findViewById(R.id.add1)
        buildDialog()

        btn.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
         if (this@YourActivity::dialog.isInitialized) { // to check if dialog is initialize or not
          dialog.show()
         }
            
            }
        })
    }

    private fun buildDialog() {
        val builder=android.app.AlertDialog.Builder(this)
        val view=layoutInflater.inflate(R.layout.dialog_dynam,null)
        val name=  view.findViewById<EditText>(R.id.nameEdit)
        builder.setView(view)
        builder.setTitle("Enter name")
            .setPositiveButton("Ok",object :DialogInterface.OnClickListener{
                override fun onClick(dialog: DialogInterface?, p1: Int) {
                addname(name.text.toString())

        // initialize dialog
        dialog = builder.create()
                }
于 2021-07-26T15:37:48.807 回答