1. 程式人生 > >EditText文字框清空效果

EditText文字框清空效果

	/**
* 動態搜尋
*/
private TextWatcher tbxSearch_TextChanged = new TextWatcher() {

// 快取上一次文字框內是否為空
private boolean isnull = true;

@Override
public void afterTextChanged(Editable s) {
Log.e(DEBUG_TAG, "TextWatcher afterTextChanged s=" + s.toString()
+ ",isnull=" + isnull);
if (TextUtils.isEmpty(s)) {
if (!isnull) {
load_url.setCompoundDrawablesWithIntrinsicBounds(null,
null, mIconSearchDefault, null);
isnull = true;
}
} else {
// if (isnull) {
load_url.setCompoundDrawablesWithIntrinsicBounds(null, null,
mIconSearchClear, null);
isnull = false;
// }
}
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}

/**
* 隨著文字框內容改變動態改變列表內容
*/
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {

}
};

private OnTouchListener txtSearch_OnTouch = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
int curX = (int) event.getX();
if (curX > v.getWidth() - 38
&& !TextUtils.isEmpty(load_url.getText())) {
load_url.setText("");
// backup the input type
int cacheInputType = load_url.getInputType();
// disable soft input
load_url.setInputType(InputType.TYPE_NULL);
// call native handler
load_url.onTouchEvent(event);
// restore input type
load_url.setInputType(cacheInputType);
// consume touch event
return true;
}
break;
}
return false;
}
};

/**
* 搜尋文字框預設圖示
*/
private Drawable mIconSearchDefault;
/**
* 搜尋文字框清除文字內容圖示
*/
private Drawable mIconSearchClear;

private EditText load_url;



/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// 設定Activity的佈局檔案
setContentView(R.layout.main);

Resources res = getResources();
mIconSearchDefault = res.getDrawable(R.drawable.txt_search_default);
mIconSearchClear = res.getDrawable(R.drawable.txt_search_clear);

load_url = (EditText) editView.findViewById(R.id.load_url);
load_url.addTextChangedListener(tbxSearch_TextChanged);
load_url.setOnTouchListener(txtSearch_OnTouch);
}



[img]http://dl.iteye.com/upload/attachment/521214/3deb239d-4f09-34c9-b232-ca8456e10530.png[/img]

[img]http://dl.iteye.com/upload/attachment/521216/b6dc944c-87c5-321d-b546-7c0e2aaa7a0e.png[/img]