EditText延迟搜索

作者: zsgnaw | 来源:发表于2017-06-26 22:14 被阅读166次
    1.gif

    使用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

    相关文章

      网友评论

        本文标题:EditText延迟搜索

        本文链接:https://www.haomeiwen.com/subject/cdzjcxtx.html