Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

仿微信模糊搜索:EditText 動態過濾 ListView 並高亮匹配

編輯:關於 Android 程式設計

模糊搜索框是 App 中很常見的需求,本文以安卓端為例,實現一個仿微信的模糊搜索效果。

先看上圖,效果還不錯。圖一為未點擊狀態,圖二為點擊之後的狀態,圖三為輸入之後的狀態。

主要功能點包括:

1、點擊後彈出懸浮層,當前 Activity 不發生跳轉;

2、實現模糊搜索,EditText 動態輸入實時過濾 ListView 的數據;

3、ListView 中包含所輸入字符的項,以不同顏色標識(高亮);

4、Json 封裝傳值;

5、EditText 帶清除按鈕(類似 ClearEditText),並自動控制軟鍵盤的顯示與隱藏。

 

看過微信等的模糊搜索後,發現原理並不難,但仍花了些時間才搗鼓出來。這裡結合相關資源,把核心代碼提取出來記錄一下,希望能幫到有需要的朋友。

一、核心控件 EditSearchView

首先是從開源項目提取的搜索控件:

private boolean mIsSearchOpen;
private boolean mClearingFocus;
private View mSearchLayout;
private View view;
private ListView mSuggestionsListView;
private EditText mSearchSrcTextView;
private ImageButton mEmptyBtn;
private TextView search_cancel;
private RelativeLayout mSearchTopBar;
private CharSequence mOldQueryText;
private CharSequence mUserQuery;
private EditSearchView.OnQueryTextListener mOnQueryChangeListener;
private EditSearchView.SearchViewListener mSearchViewListener;
private BaseAdapter mAdapter;
private EditSearchView.SavedState mSavedState;
private Context mContext;
private boolean shouldAnimate;
private final OnClickListener mOnClickListener;

public EditSearchView(Context context) {
    this(context, null);
}

public EditSearchView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public EditSearchView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs);
    this.mIsSearchOpen = false;
    this.mOnClickListener = new OnClickListener() {
        public void onClick(View v) {
            if (v == mEmptyBtn) {
                EditSearchView.this.mSearchSrcTextView.setText(null);
            } else if (v == mSearchSrcTextView) {
                EditSearchView.this.showSuggestions();
            } else if (v == search_cancel) {
                EditSearchView.this.closeSearch();
            }
        }
    };
    this.mContext = context;
    this.shouldAnimate = true;
    this.initiateView();
}

private void initiateView() {
    LayoutInflater.from(this.mContext).inflate(R.layout.search_view_layout, this, true);
    this.mSearchLayout = this.findViewById(R.id.search_layout);
    this.mSearchTopBar = (RelativeLayout) this.mSearchLayout.findViewById(R.id.search_top_bar);
    this.mSuggestionsListView = (ListView) this.mSearchLayout.findViewById(R.id.suggestion_list);
    this.mSearchSrcTextView = (EditText) this.mSearchLayout.findViewById(R.id.searchTextView);
    this.mEmptyBtn = (ImageButton) this.mSearchLayout.findViewById(R.id.action_empty_btn);
    this.search_cancel = (TextView) this.mSearchLayout.findViewById(R.id.search_cancel);
    this.mSearchSrcTextView.setOnClickListener(this.mOnClickListener);
    this.mEmptyBtn.setOnClickListener(this.mOnClickListener);
    this.search_cancel.setOnClickListener(this.mOnClickListener);
    this.initSearchView();
    this.mSuggestionsListView.setVisibility(GONE);
}

private void initSearchView() {
    this.mSearchSrcTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                hideKeyboard(v);
            }
            return true;
        }
    });
    this.mSearchSrcTextView.addTextChangedListener(new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            EditSearchView.this.mUserQuery = s;
            EditSearchView.this.startFilter(s);
            EditSearchView.this.onTextChanged(s);
        }
        public void afterTextChanged(Editable s) {}
    });
    this.mSearchSrcTextView.setOnFocusChangeListener(new OnFocusChangeListener() {
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                EditSearchView.this.showKeyboard(EditSearchView.this.mSearchSrcTextView);
                EditSearchView.this.showSuggestions();
            }
        }
    });
}

private void startFilter(CharSequence s) {
    if (this.mAdapter != null && this.mAdapter instanceof Filterable) {
        ((Filterable) this.mAdapter).getFilter().filter(s, this);
    }
}

private void onTextChanged(CharSequence newText) {
    Editable text = this.mSearchSrcTextView.getText();
    this.mUserQuery = text;
    boolean hasText = !TextUtils.isEmpty(text);
    this.mEmptyBtn.setVisibility(hasText ? VISIBLE : GONE);
    if (this.mOnQueryChangeListener != null
            && !TextUtils.equals(newText, this.mOldQueryText)) {
        this.mOnQueryChangeListener.onQueryTextChange(newText.toString());
    }
    this.mOldQueryText = newText.toString();
}

private void hideKeyboard(View view) {
    InputMethodManager imm = (InputMethodManager) view.getContext()
            .getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

private void showKeyboard(View view) {
    if (Build.VERSION.SDK_INT <= 10 && view.hasFocus()) {
        view.clearFocus();
    }
    view.requestFocus();
    InputMethodManager imm = (InputMethodManager) view.getContext()
            .getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(view, 0);
}

public void showSuggestions() {
    if (this.mAdapter != null && this.mAdapter.getCount() > 0
            && this.mSuggestionsListView.getVisibility() == GONE) {
        this.mSuggestionsListView.setVisibility(VISIBLE);
    }
}

public void setAdapter(BaseAdapter adapter) {
    this.mAdapter = adapter;
    this.mSuggestionsListView.setAdapter(adapter);
    this.startFilter(this.mSearchSrcTextView.getText());
}

public void showSearch() {
    if (this.shouldAnimate) {
        this.showSearch(true);
    } else {
        this.showSearch(false);
    }
}

public void closeSearch() {
    if (this.isSearchOpen()) {
        this.mSearchSrcTextView.setText(null);
        this.dismissSuggestions();
        this.clearFocus();
        this.mSearchLayout.setVisibility(GONE);
        if (this.mSearchViewListener != null) {
            this.mSearchViewListener.onSearchViewClosed();
        }
        this.mIsSearchOpen = false;
    }
}

public void onFilterComplete(int count) {
    if (count > 0) {
        this.showSuggestions();
    } else {
        this.dismissSuggestions();
    }
}

核心邏輯在於:為 EditText 添加 TextWatcher,在 onTextChanged 回調中實時調用 startFilter() 觸發 Adapter 的 Filter 進行過濾;同時判斷是否有輸入內容來控制清除按鈕的顯示,並通過 showKeyboard / hideKeyboard 管理軟鍵盤。

二、使用方式

在需要的地方初始化搜索事件,將數據集交給 Adapter,並為搜索框設置 Adapter 與監聽即可:

private void initSearchEvent() {
    // 綁定數據、設置 Adapter、處理 item 點擊與高亮邏輯
    ...
}

高亮部分的實現思路是:在 Adapter 的 getView 中,用 SpannableString 對命中的關鍵字設置 ForegroundColorSpan,從而在列表項中把匹配字符標記為不同顏色。

三、小結

以上就是仿微信模糊搜索的核心實現:借助 EditSearchView 封裝搜索框的顯示、隱藏與鍵盤控制,配合自定義 Filter 完成 ListView 的實時過濾,再用 SpannableString 實現關鍵字高亮。整體效果簡潔流暢,能滿足大多數列表搜索場景的需求。以上工具基於 Android Studio 開發。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved