findViewById() in Kotlin

Kotlin offers developers many time-saving features that help us create clean code. One of those features is the ability to drop the findViewById() method and replace it instead simply with the View’s id value. For example, here is an XML layout that was created in Android Studio. It includes the default EditText with an id of welcomeMessage.

Design mode in Android Studio.

The same layout is opened in Text mode below.

To access the TextView we need to use findViewById() and pass in the TextView‘s id attribute.

In lines 15-16 we get a reference to the TextView by passing findViewById it’s id. But with the introduction of Kotlin we not longer need to do this. We can simply call welcomeMessage.text = "Hi there!".

The new Kotlin way to access View’s with the id attribute.
About the author

Daniel Malone
Bringing more than a decade of software engineering experience, Daniel Malone is Editor at androidEveryday. An Austin native, Daniel is often found reading technical books, blogging and creating YouTube tutorials. When not working, he likes to listen to pop hits on Google Play Music.

Android RecyclerView Tutorial (Part 1)

  • Most apps contain lists of data using RecyclerView.
  • In this tutorial, use ConstraintLayout and Kotlin to display a list of data.

3 weeks ago

Android Architecture Components Tutorial: ViewModel + LiveData

  • Use Kotlin to build a basic Android app using Android Architecture Components.
  • As part of Jetpack, LiveData and ViewModel support a MVVM app architecture.

1 month ago

Android SharedPreferences Tutorial in Kotlin

  • Use SharedPreferences to store simple data in Android Studio projects.
  • It's good for storing small amounts of data

    1 month ago