如何解决无法从警报对话框中的 EditText 视图中获取数据
我创建了一个 alertDialog,它基本上包含两个用于输入数据的 editTexts(组件 ID,组件名称)。当用户单击警报对话框中的 yes 按钮时,新组件被添加到数据库中(截至目前我还没有为对话框中的“是”和“否”按钮添加了任何点击侦听器)但由于某种原因,我无法从编辑文本中获取数据。我是 android 应用程序开发的新手,请帮助我..... 提前致谢:)
注意: 1. 我正在使用 viewModel.flag 以便 alertDialog 在旋转时保持持久性。
- 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()
将返回 editText 对象的字符串表示形式。请参阅 String 的 toString()
方法 here 的文档。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。