Kotlin Android Extensions – No more findViewById

Kotlin Android Extensions enable us to utilize the View component (EditTexts, TextViews, Buttons,…) directly, without using findViewById.

This code sample is what we have previously covered in our tutorial. Like in the past, we’ve utilized FindViewByID to locate the views in the layout resources file (actuvity_main.xml).

class MainActivity : AppCompatActivity() {


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

        val EditText = findViewById<EditText>(R.id.radiusEditText)
        val TextView = findViewById<TextView>(R.id.introTextView)
        val TextView = findViewById<TextView>(R.id.resultTextView)
        val circlesCalc = CirclesCalc()
        //calculate circumference
        val circumButton = findViewById<Button>(R.id.circumferenceButton)
        circumButton.setOnClickListener {
            if (radiusEditText.text.toString().isEmpty()) {
                Toast.makeText(this, "Empty radius", Toast.LENGTH_LONG).show()
            } else {
                val input = radiusEditText.text.toString()
                val circumference = circlesCalc.getCircumference(input.toDouble())
                TextView.text = getString(R.string.circumference_text)
                TextView.text = circumference.toString().plus(" cm")
            }
        }
        //calculate area
        val Button = findViewById<Button>(R.id.areaButton)
        Button.setOnClickListener {
            if (radiusEditText.text.toString().isEmpty()) {
                Toast.makeText(this, "Empty radius", Toast.LENGTH_LONG).show()
            } else {
                val input = radiusEditText.text.toString()
                val area = circlesCalc.getArea(input.toDouble())
                TextView.text = getString(R.string.area_text)
                TextView.text = area.toString().plus(" cm\u00B2")
            }
        }
    }
}

It is evident that we have used findViewById to identify all EditTexts TextViews, Buttons, and TextViews. But in Kotlin there’s an awesome new method to utilize them without having to spend time creating findViewByIds.

How to Utilize Kotlin Android Extensions

Step 1: –

Add the ‘kotlin-android-extensions’ plugin to the top of the app level Gradle file. However, you don’t need to manually add it. Android Studio will automatically include it each time you start the first Kotlin project. If you’re using an earlier version of Android Studio, you may require adding this plugin by hand.

apply plugin: 'kotlin-android-extensions'

This is the way your app-level Gradle files should look.

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {

    compileSdkVersion 31
    buildToolsVersion "31.0.0"

    defaultConfig {
        applicationId "com.anushka.rvdemo1"
        minSdkVersion 26
        targetSdkVersion 31
        versionCode 1
        versionName "1.0.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

Step 2 :

Import the “kotlinx.android.synthetic” object for the layout. ( If you don’t have enabled auto import, press the Alt+Enter key combination) . You will only have to install this one time to all view components in the layout.

import kotlinx.android.synthetic.main.activity_main. *

Step 3:-

The Kotlin’s Android extension plugin enables our ability to access the parts within the activity_main.xml file by using the Ids.

In the activity_main.xml there is in the activity_main.xml file, we have a Button that has the ID ” Button” . Therefore, we can utilize that ID ” Button” directly within the MainActivity.kt.

Button.setOnClickListener {

        }

How they really work.

  • Kotlin Google Extensions creates codes based on that XML Layout file.
  • The generated code utilizes FindViewById in the background and allows us to access view components by using the IDs of the view components.
  • The plugin also creates and manages the local view cache. This improves performance by calling findViewById only once for a view component and storing it in the cache for view components instead of calling it over and repeatedly.

In the same way, we can also use other IDs, such as radiusTextView and circumferenceButton directly within the MainActivity.kt. The final codes for MainActivity.kt and activity_main.xml is provided below.

MainActivity.kt file.

class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val circlesCalc = CirclesCalc()
        circumferenceButton.setOnClickListener {

            if (radiusEditText.text.toString().isEmpty()) {
                Toast.makeText(this, "Empty radius", Toast.LENGTH_LONG).show()
            } else {
                val input = radiusEditText.text.toString()
                val circumference = circlesCalc.getCircumference(input.toDouble())
                TextView.text = getString(R.string.circumference_text)
                TextView.text = circumference.toString().plus(" cm")
            }
        }

        Button.setOnClickListener {
            if (radiusEditText.text.toString().isEmpty()) {
                Toast.makeText(this, "Empty radius", Toast.LENGTH_LONG).show()

            } else {

                val input = radiusEditText.text.toString()
                val area = circlesCalc.getArea(input.toDouble())
                TextView.text = getString(R.string.area_text)
                TextView.text = area.toString().plus(" cm\u00B2")
            }
        }
    }
}

 

activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">


    <Button
            android:id="@+id/Button"    
            android:layout_width="312dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:background="@color/colorPrimaryDark"
            android:text="@string/button"
            android:textColor="@android:color/background_light"
            android:textSize="15sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.862"
            tools:layout_editor_absoluteX="-8dp" />

    <Button
            android:id="@+id/circumferenceButton"
            android:layout_width="312dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:background="@color/colorPrimaryDark"
            android:text="@string/circumference"
            android:textColor="@android:color/background_light"
            android:textSize="15sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.731" />

    <TextView
            android:id="@+id/TextView"
            android:layout_width="0dp"
            android:layout_height="25dp"
            android:layout_margin="8dp"
            android:text="Radius(cm)"
            android:textSize="20sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="1.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.602" />

    <EditText
            android:id="@+id/EditText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:ems="10"
            android:inputType="numberDecimal"
            android:textSize="20sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.477" />




    <TextView
            android:id="@+id/introTextView"
            android:layout_width="match_parent"
            android:layout_height="36dp"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="8dp"
            android:textSize="30sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.101"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.101" />


    <TextView
            android:id="@+id/TextView"
            android:layout_width="match_parent"
            android:layout_height="41dp"
            android:layout_margin="8dp"
            android:textSize="20sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.093"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.18" />

</androidx.constraintlayout.widget.ConstraintLayout>

Read More Kotlin Tutorial: Click Here 

You may also like...