app崩溃,因为late init属性尚未在android studio中初始化

piok6c0g  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(291)

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

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

                }`
jfewjypa

jfewjypa1#

我想你有 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()
                }

相关问题