You may skip and not use the findViewById( ) in Kotlin

In Kotlin you may skip and not use the findViewById( ) and still be able to refer to UI components defined in XML Layout file. There is another way. You will need to do a couple of things first: 

  • Edit your Module/ app level build.gradle file
  • Import the data binding library into the Kotlin file (Don’t worry, Android Studio will do it for you automatically)

I assume that you know how to configure your android studio project for Kotlin. Add this line to app level gradle file:

apply plugin: 'kotlin-android-extensions'

Now sync your project. 

XML Layout File

In my case the activity xml layout file is called activity_no_find_view_by_id.xml and looks like this:

<?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"
    tools:context="com.appsdeveloperblog.kotlin.codeexamples.NoFindViewById">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />
</android.support.constraint.ConstraintLayout>

Kotlin code example

The name of my Kotlin file is NoFindViewById.kt and even though I am not using the findViewById() I can still refer the TextView with its id “textView” and for that I will need to first import my xml layout file like so:

import kotlinx.android.synthetic.main.activity_no_find_view_by_id.*

Here is my Kotlin file where you can see how the import of the elements defined in the xml layout file activity_no_find_view_by_id.xml is done. I can refer and work with my textView without the use of findViewById( ).

import android.graphics.Color
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_no_find_view_by_id.*

class NoFindViewById : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_no_find_view_by_id)
        textView.text = "Good bye \"findViewById\""
        textView.textSize = 30f
        textView.setTextColor(Color.BLACK)
    }
}

Hope this example was helpful!

If you are looking for more short code examples in Kotlin or even longer step by step Kotlin tutorials, checkout the Android->Kotlin category of this blog.

And if you are looking for books or video tutorials on Kotlin check the list of resources below. I hope you will find some of them helpful!

Happy learning Kotlin!

Building Mobile Apps with Kotlin for Android – Books


Building Mobile Apps with Kotlin for Android – Video Courses

Leave a Reply

Your email address will not be published. Required fields are marked *