使用EditText实现搜索框,优化数据请求 ,实现实时搜索展示##
image.png当EditText内容发生改变时等待1000毫秒,Message携带当前EditText的内容数据通知Hadnler去进行处理,通过判断携带数据和EditText此时的内容数据是否相同决定是否进行数据请求。减少多余的请求,提高效率
private final int searchWhat = 1;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == searchWhat) {
if (msg.obj.toString().equals(etSearch.getText().toString())) {//进行判断
pageNum = 1;
getDataList(pageNum, etSearch.getText().toString());
}
}
}
};
etSearch.addTextChangedListener(new MyTextWatcher());
List resultDataList;
public vo getDataList(int pageNum,String searchContext){
... 请求结果result 省略ListView和Adapter填充部分
resultDataList = result;
userSelectAdapter.notifyDataSetChanged();
}
private class MyTextWatcher implements TextWatcher {
@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) {
if (s.length() != 0 && s.toString().trim().length() != 0) {
Message msg = Message.obtain();
msg.what = searchWhat;
msg.obj = s.toString(); //携带当前值
mHandler.sendMessageDelayed(msg, 1000);//隔一小段时间发送msg
} else {
resultDataList.clear();
userSelectAdapter.notifyDataSetChanged();
}
}
}
网友评论