How to assign value to text view directly in Android Kotlin

In Android Studio, when referencing layout (GUI) elements, the normal flow is to use code as below:

var tv = findViewById(R.id.tv_name)

tv = myString

But, in Kotlin, Prior Android version 10, it was easy to assign values to layout elements without using find_view_by_id by simply using:

tv_name.text = myString

However, this has stopped working and to enable it, the following is the workaround:

  1. In the gradle file for the module, add id ‘kotlin-android-extensions’ in the plugins section.
  2. Then add import kotlinx.android.synthetic.main.activity_main.* in the activity kotlin code.

Now, tv_name.text = myString will work.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s