使用EditText实现搜索框,优化数据请求 ,实现实时搜索展示
-
当EditText内容发生改变时等待1000毫秒,Message携带当前EditText的内容数据通知Hadnler去进行处理
-
通过判断handler携带数据和EditText已存在的内容数据是否相同决定是否进行数据请求。
-
当handler携带数据不为空并且和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 void 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(); } } }