Android edittext editText获取文本kotlin
如何在kotlin中获取editText并与toast一起显示Android edittext editText获取文本kotlin,android-edittext,kotlin,Android Edittext,Kotlin,如何在kotlin中获取editText并与toast一起显示 var editTextHello = findViewById(R.id.editTextHello) 我试过这个,但显示了对象 Toast.makeText(this,editTextHello.toString(),Toast.LENGTH_SHORT).show() 您缺少从findViewById到EditText的视图的强制转换: var editTextHello = findViewById(R.id.editT
var editTextHello = findViewById(R.id.editTextHello)
我试过这个,但显示了对象
Toast.makeText(this,editTextHello.toString(),Toast.LENGTH_SHORT).show()
您缺少从
findViewById
到EditText
的视图的强制转换:
var editTextHello = findViewById(R.id.editTextHello) as EditText
然后,您希望在toast中显示EditText
的text
属性:
Toast.makeText(this, editTextHello.text, Toast.LENGTH_SHORT).show()
作为记录,这只是更惯用的Kotlin,相当于在EditText
上调用getText()
,就像在Java中那样:
Toast.makeText(this, editTextHello.getText(), Toast.LENGTH_SHORT).show()
使用editTextHello.text
Toast.makeText(this, editTextHello.text, Toast.LENGTH_SHORT).show()
投票的答案是正确的,但对科特林家族来说,这并不是最好的答案。如果你真的对进入这个世界感兴趣,我建议你使用扩展。通过Kotlin,您可以使用Kotlin android扩展
,您可以做到以下几点:
导入kotlinx.android.synthetic.reference\u到您的视图。editTextHello
这是:
Toast.makeText(这个,editTextHello.text,Toast.LENGTH\u SHORT).show()
请忘记getText()。。。用这个,它更干净
ps:阅读有关扩展的内容,您将看到您可以创建自己的扩展,并且可以更干净地使用Toast。大概是这样的:
fun Context.showToast(text: CharSequence, duration: Int = Toast.LENGTH_LONG) = Toast.makeText(this, text, duration).show()
在你的课堂上,它是这样使用的:
showtoos(“uhuuu”)
但这超出了我们在这里讨论的范围
发件人:
如果将edittext
设为可空,则该行将为空
Toast.makeText(this, editTextHello?.text.toString(), Toast.LENGTH_SHORT).show()
用这个来代替,它很好用
val obj=findViewById<EditText>(R.id.editText)
Toast.makeText(this,obj.text, Toast.LENGTH_LONG).show()
val obj=findViewById(R.id.editText)
Toast.makeText(this,obj.text,Toast.LENGTH\u LONG.show())
在Kotlin中,在EditText上调用.text是可以的,无需执行getText或toString
点击按钮
button?.setOnClickListener {
Toast.makeText(this,editText.text, Toast.LENGTH_LONG).show()
}
即使不需要findViewById,您也会丢失从findViewById到EditText的一组视图。
但是如果控件存在,则需要一个“if”,然后获取文本:
val editText = findViewById(R.id.editText_main) as EditText
if (editText != null) {
val showString = editText.text.toString()
Toast.makeText(this, showString, Toast.LENGTH_SHORT).show()
}
这是Kotlin,不是java。您不需要获取它的id。在kotlin中,只需写下:
var editTextHello = editTextHello.text.toString()
使用科特林的美;-)
顺便说一句,最好选择像edx_hello这样的xml ID,对于kotlin部分,选择var editTextHello。然后可以区分xml变量和kotlin变量 以维护Kotlin的标准语法使用
var editText:editText=findViewById(R.id.editTextHello)我试过了,但是我得到了错误未解析的引用textRight,类型转换也丢失了,我已经编辑了我的答案。editTextHello.text应该使用toString()为您提供一个可编辑对象将为您提供字符串。如果没有gettin ID,如何获取在Edittext中输入的值?@ArnoldBrown您需要配置才能使用它。
val editText = findViewById(R.id.editText_main) as EditText
if (editText != null) {
val showString = editText.text.toString()
Toast.makeText(this, showString, Toast.LENGTH_SHORT).show()
}
var editTextHello = editTextHello.text.toString()