Skip to main content

How to set text in a TextView in Kotlin Android

How to set text in a TextView in Kotlin Android.

Here's a step-by-step tutorial on how to set text in a TextView in Kotlin for Android.

  1. Open your Android project in Android Studio.
  2. Open the layout file (XML) where you have defined the TextView. This file is usually located in the res/layout directory and has a name like activity_main.xml or fragment_main.xml.
  3. Locate the TextView element in the XML layout file. It will have a tag <TextView> and may have various attributes like android:id, android:textSize, android:gravity, etc. Make sure you have assigned a unique android:id to the TextView; this will be used to reference it in your Kotlin code.
  4. Save the XML layout file and switch to the Kotlin code file (.kt) where you want to set the text in the TextView. This could be an Activity file, a Fragment file, or any other Kotlin class file.
  5. Inside the Kotlin code file, declare a variable to hold the reference to the TextView using the findViewById method. This method is available on any View in Android and allows you to find a view by its unique ID. Here's an example of how to declare the variable and find the TextView:
val textView = findViewById<TextView>(R.id.your_textview_id)

Replace your_textview_id with the actual ID you assigned to the TextView in the XML layout file.

  1. Now that you have a reference to the TextView, you can set its text using the text property. Here's an example of how to set the text in the TextView:
textView.text = "Hello, World!"

Replace "Hello, World!" with the text you want to display in the TextView.

  1. If you want to set the text dynamically, you can use a variable or a string resource. Here's an example of how to set the text using a variable:
val message = "Welcome to Kotlin!"
textView.text = message

And here's an example of how to set the text using a string resource:

textView.setText(R.string.app_name)

Replace R.string.app_name with the actual string resource you want to use.

  1. Finally, run your Android app on a device or emulator to see the updated text in the TextView.

That's it! You now know how to set text in a TextView in Kotlin for Android.