Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: How to get and set a text to TextView in Android using Kotlin?

I'm newbie.

I want to change text of TextView While click on it.

My code:

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

Output: I got the output but showing use property access syntax.

Can anyone tell me how to do it?

Thanks in advance.

like image 885
Nitt Avatar asked May 21 '17 12:05

Nitt


People also ask

How do I assign text to TextView?

Set The Text of The TextView You can set the text to be displayed in the TextView either when declaring it in your layout file, or by using its setText() method. The text is set via the android:text attribute. You can either set the text as attribute value directly, or reference a text defined in the strings.


1 Answers

In kotlin don't use getters and setters as like in java.The correct format of the kotlin is given below.

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

To get the values from the Textview we have to use this method

 val str: String = textView.text.toString()   println("the value is $str") 
like image 97
Nithinlal Avatar answered Sep 24 '22 02:09

Nithinlal