使用EditText实现搜索框,优化数据请求 ,实现实时搜索展示
当EditText内容发生改变时等待500毫秒,Message携带当前EditText的内容数据通知Hadnler去进行处理,通过判断携带数据和EditText此时的内容数据是否相同决定是否进行数据请求。减少多余的请求,提高效率。
关键代码
private static final int MSG_SEARCH = 1;
/**
* 定义时传入持有的Activity实例(弱引用)
*/
private Handler mHandler = new SearchHandler(this);
mBinding.searchView.etSearch.addTextChangedListener(new SearchTextWatcher());
private class SearchTextWatcher 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) {
String str = s.toString();
//文字变动 , 有未发出的搜索请求,应取消
if (mHandler.hasMessages(MSG_SEARCH)) {
mHandler.removeMessages(MSG_SEARCH);
}
if (!TextUtils.isEmpty(str)) {
//否则延迟500ms开始搜索
Message msg = Message.obtain();
msg.what = MSG_SEARCH;
//携带当前值
msg.obj = s.toString();
mHandler.sendMessageDelayed(msg, 500);
}
}
}
/**
* 自定义Handler子类
* 设置为:静态内部类
*/
private static class SearchHandler extends Handler {
// 定义 弱引用实例
private WeakReference<SeriesSearchActivity> reference;
// 在构造方法中传入需持有的Activity实例
public SearchHandler(SeriesSearchActivity activity) {
// 使用WeakReference弱引用持有Activity实例
reference = new WeakReference<SeriesSearchActivity>(activity);
}
// 通过复写handlerMessage() 从而确定更新UI的操作
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if (msg.what == MSG_SEARCH) {
SeriesSearchActivity activity = reference.get();
String searchText = activity.mBinding.searchView.etSearch.getText().toString();
if (msg.obj.toString().equals(searchText)) {
//查询搜索内容
activity.queryObjectiveCampaignByName(searchText);
}
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// 外部类Activity生命周期结束时,同时清空消息队列 & 结束Handler生命周期
mHandler.removeCallbacksAndMessages(null);
}