Kotlin:如何使用Kotlin在Android中将文本设置为TextView?

我是新手。

我想改变TextView文本,而点击它。

我的代码:

 val text: TextView = findViewById(R.id.android_text) as TextView text.setOnClickListener { text.setText(getString(R.string.name)) } 

输出:我得到的输出,但显示使用属性访问语法

谁能告诉我该怎么做?

提前致谢。

在kotlin中不要像在java中那样使用getter和setter。下面给出了kotlin的正确格式。

 val textView: TextView = findViewById(R.id.android_text) as TextView textView.setOnClickListener { textView.text = getString(R.string.name) } 

为了从Textview获取值,我们必须使用这个方法

  val str: String = textView.text.toString() println("the value is $str") 

从布局中查找文本视图。

 val textView : TextView = findViewById(R.id.android_text) as TextView 

在textview上设置onClickListener。

 textview.setOnClickListener(object: View.OnClickListener { override fun onClick(view: View): Unit { // Code here. textView.text = getString(R.string.name) } }) 

如果我们传递单个函数文字参数,则可以从View.setOnClickListener中省略参数括号。 所以,简化的代码将是:

 textview.setOnClickListener { // Code here. textView.text = getString(R.string.name) } 

Kotlin认识到常见的getX()setX(x)模式。 AxA.getX()相同,至少如果x字段在Java代码中是私有的,或者如果A是Kotlin类。

使用:

 val textView: TextView = findViewById(R.id.android_text) textView.setOnClickListener { textView.text = getString(R.string.name) } 

要么:

你可以使用@Suppress("UsePropertyAccessSyntax")来注释每个调用站点,但这很难看。