天天看點

Android搜尋建議(搜尋聯想)

Android的搜尋建議,簡言之,就是說當使用者輸入某一個關鍵詞後,系統自動給出幾個含有相近關鍵詞的搜尋建議。

效果圖如下:

MainActivity.java

package zhangphil.search;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.view.View;
import android.widget.Button;

public class MainActivity extends ActionBarActivity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		Button search = (Button) findViewById(R.id.search);
		search.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// 發起搜尋
				search();
			}
		});

		Button clear = (Button) findViewById(R.id.clear);
		clear.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				clear();
			}
		});
	}

	private void search() {
		// 向Android系統發起搜尋請求。
		this.onSearchRequested();
	}

	// onSearchRequested()方法可以重載 ,也可以不用重載。取決于是否有更多參數或資料傳遞給下一步操作。
	// 通常代碼運作邏輯需要傳遞更多資料給下一個動作時候,則可以重載此方法以完成更多資料的傳遞。
	// 如果不重載,也可以。Android系統會啟動預設的搜尋框。(在UI的上方)
	@Override
	public boolean onSearchRequested() {
		Bundle bundle = new Bundle();
		bundle.putString("some key", "some value");

		this.startSearch("輸入搜尋的關鍵詞"/** 初始化搜尋框中的提示詞 */
		, true, bundle, false /** 此處若為true,則将啟動手機上的全局設定的那個搜尋,比如Google搜尋 */
		);

		return true;
	}

	// 清除全部曆史搜尋記錄
	private void clear() {
		SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
				ZhangPhilSuggestionProvider.AUTHORITY,
				ZhangPhilSuggestionProvider.MODE);
		// 出于使用者隐私的考慮,給APP提供清除所有使用者搜尋曆史記錄的選項。
		suggestions.clearHistory();
	}
}           

onSearchRequested将觸發Android系統自動彈出搜尋框。MainActivity需要的布局檔案activity_main.xml很簡單,兩個按鈕,一個觸發搜尋事件,一個觸發清除搜尋曆史記錄動作:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <Button
        android:id="@+id/search"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/search" />

    <Button
        android:id="@+id/clear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/clear" />
    
</LinearLayout>
           

AndroidManifest.xml的内容:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="zhangphil.search"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="22" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
      
            <meta-data
                android:name="android.app.default_searchable"           
                android:value=".SearchActivity" />
        </activity>
        
        <activity
            android:name=".SearchActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>

            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" />
        </activity>

        <provider
            android:name=".ZhangPhilSuggestionProvider"
            android:authorities="ZhangPhil_AUTHORITY" />
    </application>

</manifest>           

SearchActivity.java檔案:

package zhangphil.search;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.widget.Toast;

public class SearchActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Intent intent = getIntent();
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			// 存關鍵詞
			saveMyRecentQuery(intent);
		}
	}

	private void saveMyRecentQuery(Intent intent) {
		// 把搜尋的關鍵詞儲存到Android系統的自帶的資料庫中。
		// 如無必要定制,則此過程可以使用标準、通用的方法。
		String query = intent.getStringExtra(SearchManager.QUERY);

		SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
				ZhangPhilSuggestionProvider.AUTHORITY,
				ZhangPhilSuggestionProvider.MODE);
		suggestions.saveRecentQuery(query, null);

		Toast.makeText(this, "搜尋關鍵詞:" + query ,Toast.LENGTH_LONG).show();
	}
}
           

ZhangPhilSuggestionProvider.java

package zhangphil.search;

import android.content.SearchRecentSuggestionsProvider;

public class ZhangPhilSuggestionProvider extends
		SearchRecentSuggestionsProvider {
	// 可随意定義一個可差別的字元串,但注意全局的唯一相同引用。
	public final static String AUTHORITY = "ZhangPhil_AUTHORITY";

	public final static int MODE = DATABASE_MODE_QUERIES;

	public ZhangPhilSuggestionProvider() {
		setupSuggestions(AUTHORITY, MODE);
	}
}           

searchable.xml

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="@string/search_hint" 
    android:searchSuggestAuthority="ZhangPhil_AUTHORITY"
    android:searchSuggestSelection=" ?">
</searchable>           

完整的項目全部代碼檔案我已經上傳到CSDN,可以點選下載下傳連結下載下傳到本地,解壓後導入到Eclipse運作示範。CSDN下載下傳連結:

http://download.csdn.net/detail/zhangphil/8603509