效果图
2、xml 布局
2、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:orientation="horizontal"
android:gravity="center_vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/input_search"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:layout_marginTop="5dip"
android:layout_marginBottom="5dip">
<ImageView
android:layout_width="22dip"
android:layout_height="22dip"
android:src="@drawable/icon_magnifier"
android:paddingRight="5dip"
android:layout_marginLeft="5dip"/>
<EditText
android:id="@+id/searchEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="搜索"
android:imeOptions="actionDone"
android:singleLine="true"
android:background="@null"
android:textSize="16sp"
/>
< Button
android:id="@+id/button_clear"
android:layout_width="20dip"
android:layout_height="20dip"
android:background="@drawable/icon_clear"
android:visibility="invisible"
android:layout_marginRight="8dip" />
</LinearLayout>
</LinearLayout>
3、代码
public class EdittextclearActivity 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() {
@Override
public void onClick(View v) {
searchEditText.setText("");
}
});
}
TextWatcher mTextWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
if(searchEditText.getText().toString()!=null&&!searchEditText.getText().toString().equals("")){
clearButton.setVisibility(View.VISIBLE);
}else{
clearButton.setVisibility(View.INVISIBLE);
}
}
};
}