editText get text kotlin

2020-03-11 08:43发布

How to get editText in kotlin and display with toast.

var editTextHello = findViewById(R.id.editTextHello)

I tried this but shows object

Toast.makeText(this,editTextHello.toString(),Toast.LENGTH_SHORT).show()

9条回答
神经病院院长
2楼-- · 2020-03-11 08:54

To maintain the standard syntax of Kotlin use

var editText: EditText = findViewById(R.id.editTextHello)

查看更多
干净又极端
3楼-- · 2020-03-11 08:55

In Kotlin calling .text on your EditText is fine no need to do getText or toString

Toast.makeText(this, editTextHello.text, Toast.LENGTH_SHORT).show()

with button click

button?.setOnClickListener {
        Toast.makeText(this,editText.text, Toast.LENGTH_LONG).show()
    }

Even don't need findViewById

查看更多
做个烂人
4楼-- · 2020-03-11 09:05

This is Kotlin, not java. You do not need to get the id of it. In kotlin, just write:

var editTextHello = editTextHello.text.toString()

use the beauty of kotlin ;-)

P.s: BTW, better to choose xml IDs like edx_hello and for the kotlin part, var editTextHello. Then you can differentiate between xml vars and kotlin vars.

查看更多
做个烂人
5楼-- · 2020-03-11 09:06

use editTextHello.text

  Toast.makeText(this, editTextHello.text, Toast.LENGTH_SHORT).show()
查看更多
对你真心纯属浪费
6楼-- · 2020-03-11 09:07

Use this instead it's working fine

val obj=findViewById<EditText>(R.id.editText)
Toast.makeText(this,obj.text, Toast.LENGTH_LONG).show()
查看更多
别忘想泡老子
7楼-- · 2020-03-11 09:10
Toast.makeText(this, editTextHello.text.toString(), Toast.LENGTH_SHORT).show()

If you make edittext as nullable then the line would be

Toast.makeText(this, editTextHello?.text.toString(), Toast.LENGTH_SHORT).show()
查看更多
登录 后发表回答