Clear EditText in android on button click programmatically

How to remove/delete already typed text inside edittext to empty edittext on button click dynamically.

In this tutorial we are programmatically removing the typed text from EditText so application user doesn’t need to remove text by hand back press keypad key. This will be possible using getText().clear() method. This method will first get the already typed text from edittext and then clear it. So here is the complete step by step tutorial for Clear EditText in android on button click programmatically.

android-project-download-code-button

How to Clear EditText in android on button click programmatically.

Code for MainActivity.java file.

 package com.clearedittext_android_examples.com;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

 EditText edittext;
 Button button;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 button = (Button)findViewById(R.id.button1);
 edittext = (EditText)findViewById(R.id.editText1);
 
 button.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 // TODO Auto-generated method stub
 
 //Clear EditText
 edittext.getText().clear();
 
 }
 });
 }
}

Code for activity_main.xml layout file.

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.clearedittext_android_examples.com.MainActivity" >

 <EditText
 android:id="@+id/editText1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:ems="10"
 android:hint="EditText"
 >
 </EditText>

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/editText1"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="30dp"
 android:text="Click here to clear EditText dynamically" />

</RelativeLayout>

Screenshots:

Clear EditText in android on button click programmatically

Clear EditText in android

Click here to download Clear EditText in android on button click programmatically project with source code.

Leave a Reply

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