To Add The Clear Text Button On Edit Text Follow Below Steps.
1. Create New Android Application Project. Name It As "EditTextClear".
2. Now Open Your activity_main.xml and add One Button And One EditText To It.
3. Add Any Image For Clear Text Icon To Your Drawable Name It as cleartext. We Will Set That Image To Button. My Cleartext image is
4. Type The Below Code In Your activity_main.Xml.
activity_main.xml
<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=".MainActivity" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="19dp"
android:layout_marginTop="32dp"
android:ems="10"
android:typeface="monospace" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText1"
android:layout_alignBottom="@+id/editText1"
android:layout_alignRight="@+id/editText1"
android:background="@drawable/cleartext" />
</RelativeLayout>
Your Edit Text With Clear Text Button Will Be Like Below.
5. Now Type Below Code In Your MainActivity.java file.
MainActivity.java
package
arshad.edittextclear;
import android.os.Bundle;
import
android.app.Activity;
import android.view.Menu;
import android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.Button;
import
android.widget.EditText;
import
android.widget.Toast;
public class MainActivity extends Activity {
Button Clear;
EditText text;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Clear=(Button)findViewById(R.id.button1);
text=(EditText)findViewById(R.id.editText1);
Clear.setOnClickListener(new OnClickListener (){
@Override
public void onClick(View arg0) {
// TODO Auto-generated
method stub
text.setText("");
Toast
t = Toast.makeText(getApplicationContext(),
"Text
Cleared",
Toast.LENGTH_SHORT);
t.show();
}});
}
@Override
public boolean
onCreateOptionsMenu(Menu menu) {
// Inflate the
menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
6. Now Run Your Project As Android Application.
My Output Screen's Are As Below.
All The Best :)