无法在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
         }
}


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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...