无法从警报对话框中的 EditText 视图获取数据

Unable to get the data from EditText view in the alert dialog

我创建了一个 alertDialog,它基本上包含两个用于输入数据的 editText(组件 ID、组件名称)。当用户单击警报对话框中的是按钮时,新组件将添加到数据库中(截至目前我还没有在对话框中没有为是和没有按钮添加任何单击侦听器)但由于某种原因我无法从编辑文本中获取数据。我是 android 应用程序开发的新手,请大家帮帮我......提前致谢 :)

注意: 1. 我正在使用 viewModel.flag 以便 alertDialog 保持持续旋转。

  1. onCancel() 方法只是取消 alertDialog(我打算用它来更新某些参数)。

这是创建警报对话框的 kotlin 代码。

fun onAddComponent()
    {
        val builder = AlertDialog.Builder(requireActivity())

        builder?.setTitle("New Component Info")
        val inflater = requireActivity().layoutInflater

        builder?.setView(inflater.inflate(R.layout.new_comp, null))

        builder?.setPositiveButton(R.string.Okay_button){ dialogInterface, which->
            viewModel.flag = false
            val editText : EditText? =  compAlert?.findViewById(R.id.new_Component)
            println(editText.toString())
        }
        builder?.setNegativeButton(R.string.NO){ dialogInterface, which->
            viewModel.flag = false
        }



            compAlert= builder?.create()
        compAlert?.setOnCancelListener{OnCancel()}
        viewModel.flag = true
        compAlert?.show()

    }

这是我在 onAddComponent()

中膨胀的 xml 布局
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <EditText
        android:id="@+id/new_Component"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:ems="10"
        android:hint="comp Id"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/new_component_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="comp name"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="@+id/new_Component"
        app:layout_constraintStart_toStartOf="@+id/new_Component"
        app:layout_constraintTop_toBottomOf="@+id/new_Component" />
</androidx.constraintlayout.widget.ConstraintLayout>

要在 EditText 中获取文本,您需要执行代码中的 editText.getText().toString()NOT editText.toString()

在您的代码中,editText.toString() 将 return editText 对象的字符串表示形式。请参阅 String 的 toString() 方法 here.

的文档