Clear EditText Value in Android-Kotlin

thumbnail

In this tutorial, you will learn to create button to clear edit text value in android kotlin. We will be using androidx.appcompat.widget.AppCompatEditText as edit text field for user to input username and androidx.appcompat.widget.AppCompatButton as button for user to clear the edit text field by clicking the button. Below is the source code to programmatically clear edit text value in Android-Kotlin.

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

    <androidx.appcompat.widget.AppCompatEditText
        android:id="@+id/et_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_margin="8dp"
        android:hint="Username"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btn_clear"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Clear"
        android:textColor="#ffffff"
        android:layout_margin="8dp"
        android:textStyle="bold"
        android:textSize="14sp"
        android:background="@color/colorAccent"
        app:layout_constraintTop_toBottomOf="@id/et_username"/>

</androidx.constraintlayout.widget.ConstraintLayout>

You need to import:

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

MainActivity.xml

package com.inpows.tutorial

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        btn_clear.setOnClickListener {
            et_username?.text?.clear()
        }
    }
}

The output will be:

 

Back To Top