Open In App

How to Access UI Elements Directly in Android using Kotlin Synthetic Property?

Last Updated : 01 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In android, if we want to access a UI element then we can access it by findViewById and By View, it is a very time-consuming process and decreases our development speed. In this article, we are going to see how can you directly access the UI elements by their Id. In Android, we can access UI elements directly using the synthetic property feature in Kotlin. This feature allows you to access views in your layout XML file directly in your Kotlin code without having to find them by ID. To use synthetic properties, you need to add the following line at the top of your activity/fragment file:

import kotlinx.android.synthetic.main.<your_layout_file_name>.*

This above line imports the synthetic properties for all views defined in the layout file. Then you can directly access any view in that layout file using its ID as a property.

Example:

Kotlin




textView.text = "Chinmaya"


In the above code, we can see we can access the UI element without find them by Id and set the text. By using this method we can definitely increase our development speed. The synthetic property feature can save a lot of time and make your code more readable by eliminating the need to use findViewById() method. It also reduces the risk of runtime errors caused by typos in ID names.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 2: Adding Dependency to build.gradle(Module:app)

Navigate to Gradle Scripts > build.gradle (Module:app) and add the Below dependency  under the dependencies section in the build.gradle (Module:app). If it has already their then please ignore this.

implementation 'androidx.core:core-ktx:1.7.0'

Step 3: Check for the Plugins in build.gradle(Module:app)

Navigate to Gradle Scripts > build.gradle (Module:app) and check if the below plugin is not present then add it otherwise leave it.

id 'kotlin-android-extensions'

Add the plugin to your build.gradle(Module:app) under the plugins section.

plugins {
   id 'com.android.application'
   id 'org.jetbrains.kotlin.android'
   id 'kotlin-android-extensions'
}

Step 4: Change the StatusBar Color

Navigate to app > res > values > themes > themes.xml and add the below code under the style section in the themes.xml file.

<item name="android:statusBarColor" tools:targetApi="l">#308d46</item>

Step 5: Working with activity_main.xml

Navigate to the app > res > layout > activity_main.xml and add the below code to the activity_main.xml file. Below is the code for the activity_main.xml file. The activity_main.xml represents the UI part of our application. It includes one LinearLayout oriented vertically then under the LinearLayout it contains one TextView, one EditText then one Button.

XML




<?xml version="1.0" encoding="utf-8"?>
 
<!--LinearLayout orientation vertical-->
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">
   
   <!--TextView-->
   <TextView
       android:id="@+id/tv_display_name"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       tools:text="your_name"
       android:layout_margin="20dp"
       android:textStyle="bold"
       android:textSize="20sp"
       android:textColor="@color/black"/>
   
   <!--TextInputLayout-->
   <com.google.android.material.textfield.TextInputLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_marginStart="20dp"
       android:layout_marginEnd="20dp">
      
      <!--EditText-->
      <androidx.appcompat.widget.AppCompatEditText
          android:id="@+id/et_name"
          android:background="@color/white"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:hint="Enter your name"
          android:inputType="text"
          android:textSize="15sp" />
   </com.google.android.material.textfield.TextInputLayout>
   
   <!--Button-->
   <Button
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="SUBMIT"
       android:id="@+id/btn_submit"
       android:layout_margin="20dp"/>
   
</LinearLayout>


Step 6: Working with the MainActivity File

In the MainActivity file, we implement all our functionality like applying OnClickListener to the Button, and displaying the text. Go to the MainActivity File (Navigate to app > java > YourPackageName > MainActivity) and follow the below code.  Comments are added inside the code for a better understanding of the Code. 

Kotlin




package com.example.geeksforgeeks
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
 
class MainActivity : AppCompatActivity() {
   
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        // setOnClickListener to the button
        btn_submit.setOnClickListener {
             
            // getting the text from the EditText
            val txt:String=et_name.text.toString()
             
            // display the text in the textView
            tv_display_name.setText(txt)
        }
    }
}


In this code we are applying onClickListener to the button then we get the text from the EditText then display it on the textView.

 

In the above image, we can clearly see that we can access the UI elements without find them by their IDs. Here we can directly access them in our MainActivity.

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads