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.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:id="@+id/welcomeMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

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

package com.example.findviewbyid

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        val welcomeMessage: TextView = findViewById(R.id.welcomeMessage)
        welcomeMessage.text = "Hi, I'm Daniel Malone!"
    }
}

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!".

package com.example.findviewbyid

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

//        val welcomeMessage: TextView = findViewById(R.id.welcomeMessage)
//        welcomeMessage.text = "Hi, I'm Daniel Malone!"

        welcomeMessage.text = "Hey, this is the new me!"
    }
}
The new Kotlin way to access View’s with the id attribute.

But the question is, why not use findviewbyid? It’s a lot of code to write if you just need to simply update an attribute on a view. Kotlin synthetics make it a lot easier, with a lot less code to write.

Daniel Malone 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.

1 year 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 year 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 year ago

Cleaner Architecture for Android Apps

  • Clean Architecture for Android can help developers prepare for change.
  • But app developers can't possibly know what will change.

    1 year ago

Android RecyclerView with Kotlin – Part 3

  • In part three of this series, finish creating the RecyclerView.
  • Use onBindViewHolder to display data.

1 year ago

Android RecyclerView with Kotlin – Part 2

  • Create the entire RecylerView for our UsersAdapter.
  • Continued from part 1, where we set up the Android Studio project.

1 year ago

Android and RxJava: Using a Single

  • Use RxJava's Single class when the expected type is either a success or error.
  • It's only slightly different from Observable.just(), which we discussed in the last article.

1 year ago

Android and RxJava: Getting Started

  • The powerful library RxJava can help developers build better apps.
  • See how to use Observables and Observers in this tutorial.

1 year ago

Android RecyclerView with Kotlin - Part 1

  • Oftentimes, developers need to display a list of some sort of data.
  • Whatever type of data is displayed, you should use a RecyclerView.

1 year ago

Display Sample Data when Creating a RecyclerView

  • Android Studio's default RecyclerView preview lacks sample data.
  • Adding sample data can be helpful for debugging.

1 year ago

Android Studio Tutorial with Kotlin (2018 Edition) - Part 2

  • Create a UI in Android Studio using the Design mode.
  • In this latest installment for beginners, we'll add a widget to our screen.

1 year ago