android - MaterialAlertDialogBuilder 在自定义视图 editText 上崩溃
问题描述
尝试读取 editText 内容时,AlertDialog(Material) 崩溃。
警报对话框:
MaterialAlertDialogBuilder(activity)
.setTitle(title)
.setMessage(message)
.setView(R.layout.dialog_settings_entry)
.setPositiveButton(getString(R.string.text_change)) { dialog, which ->
etUserInput.hint = message
sgr = etUserInput.text.toString() // << crashes here
dialog.dismiss()
}
.setNegativeButton(getString(android.R.string.cancel)) { dialog, _ ->
dialog.dismiss()
}
.show()
单击肯定按钮后,结果如下:
java.lang.IllegalStateException: etUserInput must not be null
at com.home.profile.SettingsFragment$buildAlertDialog$1.onClick(SettingsFragment.kt:332)
at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
etUserInput是单独布局中的简单 editText 。不确定崩溃原因。将不胜感激任何洞察它或任何有用的材料样本。
解决方案
将DialogInterface
转换为 anAlertDialog
然后使用findViewById
.
科特林:
val et = (dialog as? AlertDialog)?.findViewById<EditText>(R.id.etUserInput)
val text = et?.text.toString()
--
爪哇:
EditText et = ((AlertDialog)dialog).findViewById(R.id.etUserInput);
String text = et.getText().toString();
--
MaterialAlertDialogBuilder(activity)
.setTitle(title)
.setMessage(message)
.setView(R.layout.dialog_settings_entry)
.setPositiveButton(getString(R.string.text_change)) { dialog, which ->
val text = (dialog as? AlertDialog)?.findViewById<EditText>(R.id.etUserInput)?.text?.toString()
dialog.dismiss()
}
.setNegativeButton(getString(android.R.string.cancel)) { dialog, _ ->
dialog.dismiss()
}
.show()
推荐阅读
- javascript - 解析器继承不显示参数 typegraphql
- javascript - 如何为有评论的帖子构建 React 上下文
- filter - 如何增加片段着色器中像素之间的空间?
- deep-learning - pytorch 自定义数据集生成器中的“索引 1 超出尺寸 1 的维度 0”错误
- java - 在 Web servlet 应用程序中使用二进制数据初始化数据库
- outlook - Outlook 加载项 displayDialogAsync 在浏览器客户端中工作,而不是在完整客户端中
- python - 在饼图中的标题中添加 N
- python - 如何将新列分配给熊猫中的现有DataFrame
- kotlin - 未解决的参考:grgit
- javascript - 如何使用用户脚本(SquareSpace ESC)禁用网站使用的快捷方式?