android:
管理类代码如下:
public class KapSearchRunnableHelper implements Runnable {
private Runnable runnable = null;
public KapSearchRunnableHelper(Runnable able){
runnable = able;
}
private KapSearchRunnableHelper(){}//私有化
Handler handler = new Handler();
public void pushKeyWord(){
handler.removeCallbacks(this);// 移除请求
handler.postDelayed(this,500);// 添加请求
}
@Override
public void run() {
//此处发起Http请求
runnable.run();
}
}
使用如下:
final KapSearchRunnableHelper searchRunnableHelper = new KapSearchRunnableHelper(new Runnable() {
@Override
public void run() {
postList(0);//网络请求
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//防止铺天盖地的请求 SearchRunnable管理
searchRunnableHelper.pushKeyWord();
}
@Override
public void afterTextChanged(Editable editable) {
}
});
iOS:
代码如下:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
//实时搜索(连续输入的时候不请求)
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(postList:) object:searchBar];
[self performSelector:@selector(postList:) withObject:searchBar afterDelay:0.1];
}