editText获取文本kotlin

use*_*518 9 android-edittext kotlin

如何在kotlin中获取editText并使用toast显示.

var editTextHello = findViewById(R.id.editTextHello)
Run Code Online (Sandbox Code Playgroud)

我尝试了这个,但显示了对象

Toast.makeText(this,editTextHello.toString(),Toast.LENGTH_SHORT).show()
Run Code Online (Sandbox Code Playgroud)

zsm*_*b13 13

你缺少的一投View,你从中获取findViewByIdEditText:

var editTextHello = findViewById(R.id.editTextHello) as EditText
Run Code Online (Sandbox Code Playgroud)

然后,您要显示吐司中的text属性EditText:

Toast.makeText(this, editTextHello.text, Toast.LENGTH_SHORT).show()
Run Code Online (Sandbox Code Playgroud)

为了记录,这只是更像惯用的Kotlin等同于调用getText()你的EditText,就像你用Java做的那样:

Toast.makeText(this, editTextHello.getText(), Toast.LENGTH_SHORT).show()
Run Code Online (Sandbox Code Playgroud)

  • editTextHello.text 应该给你一个可编辑的对象,使用 toString() 会给你字符串。 (3认同)

Meh*_*ran 11

这是Kotlin,不是java。您无需获取其ID。在Kotlin中,只需编写:

var editTextHello = editTextHello.text.toString()
Run Code Online (Sandbox Code Playgroud)

使用科特林的美丽;-)

附:顺便说一句,最好选择edx_hello之类的xml ID,对于kotlin部分,最好选择var editTextHello。然后,您可以区分xml var和kotlin var。

  • @ArnoldBrown,您需要配置 [Kotlin Android 扩展插件](https://kotlinlang.org/docs/tutorials/android-plugin.html#view-binding) 才能使用它。 (2认同)