How to clear the text of an EditText in Kotlin Android
How to clear the text of an EditText in Kotlin Android.
Here's a step-by-step tutorial on how to clear the text of an EditText in Kotlin for Android:
Step 1: Create a new Android project
- Open Android Studio and create a new Android project with an empty activity.
Step 2: Add an EditText to the layout file
Open the activity_main.xml layout file located in the res/layout directory.
Add the following code inside the
<RelativeLayout>or<LinearLayout>tags:<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter text here" />
Step 3: Initialize the EditText in the activity
Open the MainActivity.kt file located in the java/(package-name) directory.
Inside the
onCreate()method, add the following code to initialize the EditText:val editText = findViewById<EditText>(R.id.editText)
Step 4: Clear the EditText text
To clear the text of the EditText, you can use the
setText()method and pass an empty string as the argument.Add the following code inside the
onCreate()method to clear the EditText text when a button is clicked:val clearButton = findViewById<Button>(R.id.clearButton)
clearButton.setOnClickListener {
editText.setText("")
}
Step 5: Run the application
- Connect your Android device or start an emulator.
- Run the application and you should see the EditText with a hint text and a clear button.
- When you enter some text in the EditText and click the clear button, the text should be cleared.
That's it! You have successfully cleared the text of an EditText in Kotlin for Android. You can customize this code example by adding additional functionality or modifying the UI as per your requirements.