Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 入門:在 Google Map 上打造內建浮動搜尋框

編輯:Android 開發實例

在 Map 應用中經常會看到一個浮動的搜尋框,多半用來搜尋附近的 POI 點,而且這些功能長得都大同小異。查了一下才發現,SDK 的 Dev Guide 早有詳細介紹,只是全英文,讀起來頗費工夫。功能本身並不難,麻煩的是配置瑣碎,以下逐步說明。

一、搜尋框配置檔 searchable.xml

這是一個用來設定應用程式搜尋框的 XML 檔,通常命名為 searchable.xml,並放在專案的 res/xml/ 目錄下。根節點必須是 searchable。在 SearchableInfo 中,Android 透過 com.android.internal.R.styleable.Searchable 這個 ID 讀取配置,因此標籤名稱必須固定為 searchable;至於檔名則無關緊要,重點是一定要放進 res/xml/ 目錄。內容大致如下:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <searchable xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:label="@string/searchLabel" android:hint="@string/searchHint" 
  4.     android:icon="@drawable/menu_route" android:searchSuggestAuthority="com.debby.googlemap.SuggestionProvider" 
  5.     android:queryAfterZeroResults="false" android:searchSuggestSelection=" ? "> 
  6. </searchable> 

其中 android:icon 原以為能設定搜尋文字前方那個 View 的圖示,實測卻不起作用,文件中也未提及,看來確實無效,這屬性讓我折騰了好久,留待後續再談。另外要注意,android:label 與 android:hint 不能直接寫字面值,而必須指向 values 中定義的字串資源;其中 android:hint 就是輸入框為空時顯示的提示文字。

此外還有大量與語音搜尋相關的配置,這個功能相對冷門,有興趣者可自行查閱文件。完整的屬性清單如下:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <searchable xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:label="string resource" 
  4.     android:hint="string resource" 
  5.     android:searchMode=["queryRewriteFromData" | "queryRewriteFromText"] 
  6.     android:searchButtonText="string resource" 
  7.     android:inputType="inputType" 
  8.     android:imeOptions="imeOptions" 
  9.     android:searchSuggestAuthority="string" 
  10.     android:searchSuggestPath="string" 
  11.     android:searchSuggestSelection="string" 
  12.     android:searchSuggestIntentAction="string" 
  13.     android:searchSuggestIntentData="string" 
  14.     android:searchSuggestThreshold="int" 
  15.     android:includeInGlobalSearch=["true" | "false"] 
  16.     android:searchSettingsDescription="string resource" 
  17.     android:queryAfterZeroResults=["true" | "false"] 
  18.     android:voiceSearchMode=["showVoiceSearchButton" | "launchWebSearch" | "launchRecognizer"] 
  19.     android:voiceLanguageModel=["free-form" | "web_search"] 
  20.     android:voicePromptText="string resource" 
  21.     android:voiceLanguage="string" 
  22.     android:voiceMaxResults="int" 
  23.     > 
  24.     <actionkey 
  25.         android:keycode="KEYCODE" 
  26.         android:queryActionMsg="string" 
  27.         android:suggestActionMsg="string" 
  28.         android:suggestActionMsgColumn="string" > 
  29. </searchable> 

二、建立負責搜尋的 Activity

這個 Activity 可以新建,也可以直接用彈出搜尋框的當前 Activity。本文的 MapActivity 就是顯示結果的地方,因此直接沿用。兩種做法配置相近,差別在於結果接收的方式。首先在 Activity 標籤中加入 intent-filter 與 meta-data:

  1. <intent-filter>  
  2.                 <action android:name="android.intent.action.SEARCH" />  
  3.             </intent-filter>  
  4.             <meta-data android:name="android.app.searchable"  
  5.                        android:resource="@xml/searchable"/>  

這樣只在該 Activity 中啟用搜尋。若希望整個 Application 都能使用搜尋,則需建立一個專門處理搜尋的 Activity,並在 application 標籤下宣告預設 searchable:

  1. <!-- declare the default searchable Activity for the whole app --> 
  2.    <meta-data android:name="android.app.default_searchable" 
  3.                    android:value=".MySearchableActivity" /> 

三、呼叫搜尋框

所有 Activity 都能呼叫 onSearchRequested() 讓搜尋框出現。測試時有個小技巧:在 onCreate() 中呼叫 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL),使用者按下實體鍵盤按鍵時就會自動啟動搜尋框。若想觸發時順便做別的事,可覆寫 onSearchRequested():

  1. @Override 
  2. public boolean onSearchRequested() {  
  3. //這個方法中干你想干的事  
  4.     doSometingOther();  
  5.     return super.onSearchRequested();  
  6. } 

呼叫時若想傳遞參數,可以改用 startSearch():

  1. public boolean onSearchRequested() {  
  2.         Log.i(TAG,"onSearchRequested------------========");  
  3.         Bundle appData = new Bundle();  
  4.         appData.putString("key", "your info");  
  5.         startSearch(null, true, appData, false);  
  6.         return true;  
  7.     } 

四、接收查詢條件並執行查詢

若是專門處理查詢的 Activity,可直接在 onCreate 中執行:

  1. @Override 
  2. public void onCreate(Bundle savedInstanceState) {  
  3.     super.onCreate(savedInstanceState);  
  4.     setContentView(R.layout.search);  
  5.     Intent intent = getIntent();  
  6.     if (Intent.ACTION_SEARCH.equals(intent.getAction())) {  
  7.       String query = intent.getStringExtra(SearchManager.QUERY);  
  8.       doMySearch(query);  
  9.     }  
  10. } 

但若是沿用當前 Activity,onCreate 只會執行一次,此時就必須靠 onNewIntent 來接收:

  1. @Override 
  2. public void onCreate(Bundle savedInstanceState) {  
  3.     super.onCreate(savedInstanceState);  
  4.     setContentView(R.layout.search);  
  5.     handleIntent(getIntent());  
  6. }  
  7.  
  8. @Override 
  9. protected void onNewIntent(Intent intent) {  
  10.     setIntent(intent);  
  11.     handleIntent(intent);  
  12. }  
  13.  
  14. private void handleIntent(Intent intent) {  
  15.     if (Intent.ACTION_SEARCH.equals(intent.getAction())) {  
  16.       String query = intent.getStringExtra(SearchManager.QUERY);  
  17.       doMySearch(query);  
  18.     }  
  19. } 

如此便會透過 doMySearch() 完成查詢。不過要注意:查詢完按返回時,你會發現 Activity 堆疊裡有兩個 MapActivity 實例,這可以透過 android:launchMode="singleTop" 解決:

  1. <activity android:name=".GoogleMapActivity" android:launchMode="singleTop" 
  2.                   android:label="@string/app_name"> 
  3.             <intent-filter> 
  4.                 <action android:name="android.intent.action.MAIN" /> 
  5.                 <category android:name="android.intent.category.LAUNCHER" /> 
  6.             </intent-filter> 
  7.             <intent-filter>  
  8.                 <action android:name="android.intent.action.SEARCH" />  
  9.             </intent-filter>  
  10.             <meta-data android:name="android.app.searchable"  
  11.                        android:resource="@xml/searchable"/>  
  12.            </activity> 

五、記錄歷史關鍵字

查詢完成後,往往希望能保存這次的查詢條件。Android 透過 SearchRecentSuggestionsProvider 實作了保存關鍵字的功能。首先建立一個 Provider 類:

  1. public class SearchSuggestionProvider extends SearchRecentSuggestionsProvider {  
  2.     /**  
  3.      * Authority  
  4.      */ 
  5.     final static String AUTHORITY = "com.debby.googlemap.SuggestionProvider";  
  6.     /**  
  7.      * Mode  
  8.      */ 
  9.     final static int MODE = DATABASE_MODE_QUERIES;  
  10.     public SearchSuggestionProvider() {  
  11.         super();  
  12.         setupSuggestions(AUTHORITY, MODE);  
  13.     }  
  14. } 

接著在 Manifest 中註冊,注意 android:authorities 要與 Provider 內保持一致:

  1. <provider android:name="com.debby.googlemap.SearchSuggestionProvider" 
  2.                 android:authorities="com.debby.googlemap.SuggestionProvider" /> 

如此一來,就能在 Activity 中呼叫保存:

  1. SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this, 
  2.                 SearchSuggestionProvider.AUTHORITY, SearchSuggestionProvider.MODE);  
  3. suggestions.saveRecentQuery(query, null); 

這樣關鍵字就保存成功,下次搜尋時即可看到歷史紀錄。有些時候我們還想保存查詢結果,例如在地圖上查過某個地點,希望下次能快速重現——這時可以把該地點的經緯度等資訊存起來,直接在 handleIntent() 中透過 SQLite 手動操作資料庫即可,屬於一般資料庫操作,這裡不再贅述。

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