當您需要在您的應用程式中提供搜尋服務時,您第一個想到的是您的搜尋方塊要放哪呢?通過使用Android的搜尋方塊架,應用程式將顯示一個自訂搜尋對話方塊來處理使用者的搜尋請求。通過一個簡單的搜尋按鈕或從您的應用程式中調用API,搜尋對話方塊就會顯示在螢幕的頂部,並會自動顯示您的應用程式圖示。
本文將教你如何為你的應用程式提供一個自訂搜尋對話方塊。這樣做,給您的使用者提供一個標準化的搜尋體驗,並能增加如語音搜尋和搜尋建議等功能
使用步驟:
一,AndroidManifest.xml 配置
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="tianshuai.uc" android:versionCode="1" android:versionName="1.0"> <application android:label="@string/app_name" android:icon="@drawable/icon"> <activity android:name="MainActivity" android:label="@string/app_name" android:launchMode="singleTop" > //這裡不用每次調用搜尋方塊都執行Oncreat,建立一個Activity 這樣 完全關閉時候麻煩 <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.SEARCH" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> //設定檔 <meta-data android:name="android.app.searchable" android:resource="@layout/searchable"/> </activity> //指定相應的Activity類 <meta-data android:name="android.app.default_searchable" android:value=".MainActivity" /> </application> <uses-permission android:name="android.permission.INTERNET"/></manifest>
二,layout/searchable.xml
<?xml version="1.0" encoding="utf-8"?><searchable xmlns:android="http://schemas.android.com/apk/res/android" android:label="@string/searchLabel" android:hint="@string/searchHint" android:icon="@drawable/horse" android:searchSuggestAuthority="com.debby.googlemap.SuggestionProvider" android:queryAfterZeroResults="false" android:searchSuggestSelection=" ? "> </searchable>
三,MainActivity.java
@Override protected void onNewIntent(Intent intent) { setIntent(intent); handleIntent(intent); } private void handleIntent(Intent intent) { if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); if(!query.startsWith("http://")){ mWebView.loadUrl("http://"+query); } if(query.startsWith("http://")){ mWebView.loadUrl(query); } } }
public boolean onKeyDown(int keyCode, KeyEvent event) { //手機按鍵 //搜尋按鍵 if(keyCode == KeyEvent.KEYCODE_SEARCH){//調用搜尋方塊 onSearchRequested(); }
public boolean onSearchRequested(){ this.startSearch(null, false, null, false); return true; }
對於以上有不明白指出,或者有錯誤指出,歡迎批評指正。