在工作中会碰到使用EditText作为搜索框的时监听TextWatsher事件能让我们实时拿到EditText中的内容,但是TextWatsher给我们的三个接口
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
会在每次数据改变的时候都会调用,每次输入或者删除一个字符的时候都会将我们的逻辑执行一边,但是这不是我们想要的,我们的想法是在它输入完成后再执行后面的逻辑,比如查询数据库等操作。刚开始的思路是监听键盘上的完成按键,但是很尴尬,没有找到解决方案。后来想到可以用延时来实现我们的功能。具体看代码:
@Override
public void afterTextChanged(Editable s) {
edit_text = s.toString;
if (mHandler.hasMessages(3)) {
mHandler.removeMessages(3);
}
mHandler.sendEmptyMessageDelayed(3, 1000);
}
另外,如果不需要对每次输入的东西都进行监听的话可以设置键盘的样式,让用户点击搜索按键或者点击完成按键然后在进行后续操作,这样的话需要在布局文件中添加EditText的属性:
android:imeOptions="actionSearch" android:inputType="text" 或者:
android:imeOptions="actionDone" android:inputType="text" 然后监听EditText的事件
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH){//搜索按键action{ } return false; } });