使用Handler的延迟发送实现:
private static final int MESSAGE_SEARCH = 0x1;
private static long INTERVAL = 1000; // 输入变化时间间隔
Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == MESSAGE_SEARCH){
mTextView.setText("搜索key:" + mEditText.getText().toString());
}
}
};
// 设置监听
mEditText.addTextChangedListener(new 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 (mHandler.hasMessages(MESSAGE_SEARCH)) {
mHandler.removeMessages(MESSAGE_SEARCH);
}
mHandler.sendEmptyMessageDelayed(MESSAGE_SEARCH, INTERVAL);
}
});
一般使用Handler会有一个内存泄漏的提示:
Paste_Image.png可以使用WeakReference弱引用来避免:
MyHandler mHandler = new MyHandler(this);
private static class MyHandler extends Handler {
WeakReference<SearchEditActivity> mActivityReference;
MyHandler(SearchEditActivity activity) {
mActivityReference= new WeakReference<SearchEditActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
SearchEditActivity activity = mActivityReference.get();
if (activity != null) {
activity.handleMessage(msg);
}
}
}
private void handleMessage(Message message){
if (message.what == MESSAGE_SEARCH){
mTextView.setText("搜索key:" + mEditText.getText().toString());
}
}
Paste_Image.png
网友评论