布局文件main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dip"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:layout_marginTop="5dip"
android:gravity="center_vertical"
android:orientation="horizontal" >

<EditText
android:id="@+id/searchEditText"
android:layout_width="fill_parent"
android:layout_height="45sp"
android:layout_weight="1"
android:hint="搜索"
android:imeOptions="actionDone"
android:singleLine="true"
android:textSize="16sp" />

<Button
android:id="@+id/button_clear"
android:layout_width="40sp"
android:layout_height="40sp"
android:layout_marginRight="8dip"
android:background="@drawable/icon_clear"
android:visibility="invisible" />
</LinearLayout>

</LinearLayout>

.java文件如下:

package org.lxh.demo;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Hello extends Activity {

EditText searchEditText;
Button clearButton;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

searchEditText = (EditText) findViewById(R.id.searchEditText);
clearButton = (Button) findViewById(R.id.button_clear);

searchEditText.addTextChangedListener(mTextWatcher);
clearButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
searchEditText.setText("");
}
});
}

TextWatcher mTextWatcher = new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}

public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}

public void afterTextChanged(Editable s) {
if (searchEditText.getText().toString() != null
&& !searchEditText.getText().toString().equals("")) {
clearButton.setVisibility(View.VISIBLE);
} else {
clearButton.setVisibility(View.INVISIBLE);
}
}
};
}

运行实例如下:

TextWatcher实现一键清空EditText_xml

界面丑的一米,功能是实现了。