一、實作效果
二、實作代碼
監聽輸入
/**
* 動态搜尋
*/
private TextWatcher tbxSearch_TextChanged = new TextWatcher() {
//緩存上一次文本框内是否為空
private boolean isnull = true;
@Override
public void afterTextChanged(Editable s) {
if (TextUtils.isEmpty(s)) {
if (!isnull) {
mSearchView.setCompoundDrawablesWithIntrinsicBounds(null,
null, mIconSearchDefault, null);
isnull = true;
}
} else {
if (isnull) {
null, mIconSearchClear, null);
isnull = false;
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
/**
* 随着文本框内容改變動态改變清單内容
*/
public void onTextChanged(CharSequence s, int start, int before,
int count) {
};
觸摸事件
private OnTouchListener txtSearch_OnTouch = new OnTouchListener() {
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(mSearchView.getText())) {
mSearchView.setText("");
int cacheInputType = mSearchView.getInputType();// backup the input type
mSearchView.setInputType(InputType.TYPE_NULL);// disable soft input
mSearchView.onTouchEvent(event);// call native handler
mSearchView.setInputType(cacheInputType);// restore input type
return true;// consume touch even
break;
return false;
綁定事件
private Drawable mIconSearchDefault; // 搜尋文本框預設圖示
private Drawable mIconSearchClear; // 搜尋文本框清除文本内容圖示
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main)
final Resources res = getResources();
mIconSearchDefault = res.getDrawable(R.drawable.txt_search_default);
mIconSearchClear = res.getDrawable(R.drawable.txt_search_clear);
mSearchView = (EditText) findViewById(R.id.txtSearch);
mSearchView.addTextChangedListener(tbxSearch_TextChanged);
mSearchView.setOnTouchListener(txtSearch_OnTouch);
}
代碼說明:
1. 為輸入框綁定觸摸事件(模拟點選事件捕捉)。通過監聽點選區域判斷是否點選清空圖檔,如果在該區域并且文本框不為空,則清空文本框。
2. 為輸入框綁定文本改變事件監聽,根據内容改變動态設定圖示顯示。
3. 維持清空操作後軟鍵盤狀态。
三、參考
四、小圖示下載下傳
(右鍵另存為即可。)