天天看點

Android SearchView介紹及搜尋提示實作

本文主要介紹SearchView的使用、即時搜尋提示功能的實作,以及一些設定。

Android SearchView介紹及搜尋提示實作

1. layout檔案

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent" >

<SearchView

android:id="@+id/search_view"

android:layout_height="match_parent"

android:iconifiedByDefault="true"

android:inputType="textCapWords"

android:imeOptions="actionSearch"

android:queryHint="" />

</RelativeLayout>

xml中主要配置有四個屬性,如下:

android:iconifiedByDefault表示搜尋圖示是否在輸入框内。true效果更加

android:imeOptions設定IME options,即輸入法的Enter鍵的功能,可以是搜尋、下一個、發送、完成等等。這裡actionSearch表示搜尋

android:inputType輸入框文本類型,可控制輸入法鍵盤樣式,如numberPassword即為數字密碼樣式

android:queryHint輸入框預設文本

2. java部分代碼

SearchView幾個主要函數

setOnCloseListener(SearchView.OnCloseListener listener)表示點選取消按鈕listener,預設點選搜尋輸入框

setOnQueryTextListener(SearchView.OnQueryTextListener listener)表示輸入框文字listener,包括public boolean onQueryTextSubmit(String query)開始搜尋listener,public boolean onQueryTextChange(String newText)輸入框内容變化listener,兩個函數,下面代碼包含了如何利用延遲執行實作搜尋提示

Java部分實作

上面代碼在onQueryTextChange函數即輸入框内容每次變化時将一個資料擷取線程SearchTipThread放到ScheduledExecutorService中,500ms後執行,線上程執行時判斷目前輸入框内容和要搜尋内容,若相等則繼續執行,否則直接傳回,避免不必要的資料擷取和多個搜尋提示同時出現。

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE

| WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

表示預設輸入法彈出

編輯框内容為空點選取消的x按鈕,編輯框收縮,可在onClose中傳回true

searchView.setOnCloseListener(new OnCloseListener() {

@Override

public boolean onClose() {

return true;

}

});

searchView.onActionViewExpanded();表示在内容為空時不顯示取消的x按鈕,内容不為空時顯示.

searchView.setSubmitButtonEnabled(true);編輯框後顯示search按鈕,個人建議用android:imeOptions=”actionSearch”代替。

隐藏輸入法鍵盤

InputMethodManager inputMethodManager;

inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

private void hideSoftInput() {

if (inputMethodManager != null) {

View v = SearchActivity.this.getCurrentFocus();

if (v == null) {

return;

inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(),

InputMethodManager.HIDE_NOT_ALWAYS);

searchView.clearFocus();

其中SearchActivity為Activity的類名

繼續閱讀