android - 无法在android中使用对话框
问题描述
我正在尝试在 android 中创建一个带有编辑文本的对话框,此编辑文本将一些文本返回到主要活动中的片段
class NameDialog : AppCompatDialogFragment() {
private lateinit var listener: NameDialogListener
override fun onAttach(context: Context) {
super.onAttach(context)
try{
listener = context as NameDialogListener
}catch (e:Exception){
Timber.d("Must implement NameDialog Listener")
e.printStackTrace()
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder : AlertDialog.Builder = AlertDialog.Builder(activity)
val layoutInflater = requireActivity().layoutInflater
val view = layoutInflater.inflate(R.layout.name_dialog_box , null)
val editText = view.findViewById<TextInputEditText>(R.id.Dialog_textField)
builder.setView(view)
.setTitle("Change Handle")
.setNegativeButton("Cancel") { _, _ -> }
.setPositiveButton("Confirm") { _, _ ->
val handle = editText.text.toString()
listener.applyUsername(handle)
}
return builder.create()
}
interface NameDialogListener{
fun applyUsername(handle :String)
}
}
但是,当我单击对话框上的肯定按钮时,我的应用程序崩溃并显示此错误消息
kotlin.UninitializedPropertyAccessException: lateinit property listener has not been initialized
at com.carrot.trucoder2.utils.NameDialog.access$getListener$p(NameDialog.kt:13)
at com.carrot.trucoder2.utils.NameDialog$onCreateDialog$2.onClick(NameDialog.kt:40)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:177)
at android.os.Handler.dispatchMessage(Handler.java:107)
这是我的片段
class SettingsFragment : Fragment(R.layout.fragment_settings) , NameDialog.NameDialogListener {
val viewModel: DetailsViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
button.setOnClickListener{
openDialog()
}
}
private fun openDialog(){
val dialog = NameDialog()
dialog.show(childFragmentManager , "Name change Dialog")
}
override fun applyUsername(handle: String) {
//toast handle
}
}
有人可以帮我解决这个问题吗?谢谢 :-)
解决方案
推荐阅读
- angular - 我想使用反应式表单方法对我的动态选项卡表单进行验证
- c++ - 如何在 MFC 应用程序中获取列表控件的已编辑子项索引
- angular - Kendo Angular 动态网格自定义对象格式
- angular - 离子和角度 ngModel 无法正常工作
- c# - 更改自动更正上下文菜单的样式
- wordpress - 在 woocommerce_form_field 中设置动态选项数组
- r - 使用 R Shiny 中的滑块触发音频文件
- vb.net - 将 LINQ 数据放入 DataTable
- aem - AEM cq/dialog和granite/dialog有什么区别
- c# - 在 WPF DataGrid 中添加按钮并与之交互