首页 > 解决方案 > 无法在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
         }
}


有人可以帮我解决这个问题吗?谢谢 :-)

标签: androidkotlinandroid-alertdialog

解决方案


推荐阅读