如何从用户那里获得名称,并使用Kotlin在Toast中显示它?

问题描述 投票:0回答:1

我创建了一个包含EditText的自定义对话框,以使用户输入其名称。当用户单击“保存”时,我想在Toast中显示他的名字。我做了下面的代码,但是当我单击“保存”时,应用程序一直停止。我想知道错误在哪里?

change_name.setOnClickListener {
    val builder = AlertDialog.Builder(this)
    val inflater =  LayoutInflater.from(this).inflate(R.layout.dialog_name,null,false)
    builder.setView(inflater)
    builder.setPositiveButton("SAVE") { dialog, id ->
        val name = entered_name.text.toString()
        Toast.makeText(this,name,Toast.LENGTH_LONG).show()
    }

    builder.create().show()
}
android kotlin android-edittext
1个回答
0
投票

欢迎Omar加入SO社区。

在您的代码中,您正在做的是创建自定义对话框,并调用提供正按钮的对话框onClick,我确定您的代码在此行代码处崩溃

val name = entered_name.text.toString()

因为它没有直接获得EditText的合成属性。

您需要稍微修改一下代码。

val builder = AlertDialog.Builder(this)
val inflater =  LayoutInflater.from(this).inflate(R.layout.dialog_name,null,false)
builder.setView(inflater)
val yourEditText :EditText = inflater.findViewById(R.id.entered_name)
builder.setPositiveButton("SAVE") { dialog, id ->
    val name = yourEditText.text.toString()
    Toast.makeText(this,name,Toast.LENGTH_LONG).show()
}

builder.create().show()
© www.soinside.com 2019 - 2024. All rights reserved.