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
.

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

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.