Android 搜索框 search dialog 和 search widget

分爲search dialog和search widgethtml

區別:android

A,search dialog是一個被系統控制的UI組件。但他被用戶激活的時候,它老是出如今activity的上。

B,Android系統負責處理search dialog上全部的事件,當用戶提交了查詢,系統會把這個查詢請求傳輸到咱們的searchable activity,讓searchable activity在處理真正的查詢。當用戶在輸入的時候,search dialog還能提供搜索建議。

C,search widget是SearchView的一個實例,你能夠把它放在你的佈局的任何地方。

D,默認的,search widget和一個標準的EditText widget同樣,不能作任何事情。
可是你能夠配置它,讓android系統處理全部的按鍵事件,把查詢請求傳輸給合適的activity,能夠配置它讓它像search dialog同樣提供search suggestions。

E,search widget在 Android 3.0或更高版本纔可用. search dialog沒有此項限制

##search dialog基礎##git

原理:github

當用戶在search dialog或search widget中執行一個搜索的時候,系統會建立一個Intent,並把查詢關鍵字保存在裏面,而後啓動咱們在AndroidManifest.xml中聲明好的searchable activity,並把Intent傳送給它。數據庫

步驟:數組

一、res/menu 目錄下 建立menu資源文件 menu_main.xmlapp

<item
	android:id="@+id/menu_search"
	android:title="查詢"
	app:actionViewClass="android.support.v7.widget.SearchView"
	app:showAsAction="collapseActionView|ifRoom"
	/>

二、重寫onCreateOptionsMenu方法ide

[@Override](https://my.oschina.net/u/1162528)
	public boolean onCreateOptionsMenu(Menu menu) {
	
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.menu_main, menu);
		SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
		searchView.setIconifiedByDefault(false); // 是否默認顯示圖標
		searchView.setSubmitButtonEnabled(false); // 是否顯示提交按鈕
	}

三、建立處理搜索的searchable activity佈局

<activity android:name=".SearchResultsActivity" android:launchMode="singleTop">
        <intent-filter>
            <action android:name="android.intent.action.SEARCH"/>
        </intent-filter>

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

四、建立res/xml/searchable.xml資源文件ui

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
			android:label="@string/app_name"
			android:hint="@string/search_hint"
			android:icon="@mipmap/icon"
	>

	</searchable>

五、onCreateOptionsMenu中增長處理代碼

SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
	// 設置處理搜索的activity
	//ComponentName componentName = getComponentName(); // 當前Activity
	ComponentName componentName = new ComponentName(this, SearchResultsActivity.class); // 指定Activity
	SearchableInfo searchableInfo = searchManager.getSearchableInfo(componentName);
	searchView.setSearchableInfo(searchableInfo);

六、在SearchResultsActivity中處理搜索

@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_results);

		handleIntent(getIntent());
	}

	@Override
	protected void onNewIntent(Intent intent) {
		setIntent(intent);
		handleIntent(getIntent());
	}

	private void handleIntent(Intent intent) {

		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);
			Log.d(TAG, query + "==");
		}
	}

##search dialog 最近搜索提示##

一、建立搜索提示的SuggestionProvider內容提供者

public class MySuggestionProvider extends SearchRecentSuggestionsProvider {

		private static final String TAG = "MySuggestionProvider";
		
		public final static String AUTHORITY = "com.df.searchview.MySuggestionProvider";
		public final static int MODE = SearchRecentSuggestionsProvider.DATABASE_MODE_QUERIES;

		public MySuggestionProvider(){
			Log.d(TAG, "=MySuggestionProvider=");
			setupSuggestions(AUTHORITY, MODE);
		}
	}

二、配置manifest

<provider
        android:name=".MySuggestionProvider"
        android:authorities="com.df.searchview.MySuggestionProvider"
        />

三、SearchResultsActivity中添加最近搜索數據

private void handleIntent(Intent intent) {

		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			Log.d(TAG, "=Intent.ACTION_SEARCH=");
			String query = intent.getStringExtra(SearchManager.QUERY);
			Log.d(TAG, query + "==");

			SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
					MySuggestionProvider.AUTHORITY, MySuggestionProvider.MODE);
			suggestions.saveRecentQuery(query, null);  // 保存最近的數據
		}
	}

四、配置searchable

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
        android:label="@string/app_name"
        android:hint="@string/search_hint"
        android:icon="@mipmap/icon"
        android:searchSuggestAuthority="com.df.searchview.MySuggestionProvider"
        android:searchSuggestSelection=" ?"
		>

	</searchable>

五、清除查詢數據

SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
    MySuggestionProvider.AUTHORITY, MySuggestionProvider.MODE);
	suggestions.clearHistory();

##search dialog 自定義Suggestions##

一、建立自定義內容提供者

public class MyCustomSuggestionProvider extends ContentProvider {
	
		private static final String TAG = "CustomSugProvider";

		public final static String AUTHORITY = "com.df.searchview.MyCustomSuggestionProvider";

		public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/suggest");

		private SuggestDao suggestDao; // 數據庫訪問類

		private static final UriMatcher uriMatcher = buildUriMatcher();

		private static UriMatcher buildUriMatcher() {

			UriMatcher matcher =  new UriMatcher(UriMatcher.NO_MATCH);

			// 查詢
			matcher.addURI(AUTHORITY, "suggest", 0);
			matcher.addURI(AUTHORITY, "suggest/#", 1);

			// 搜索提示
			matcher.addURI(AUTHORITY, "dfoptional/" + SearchManager.SUGGEST_URI_PATH_QUERY, 0);
			matcher.addURI(AUTHORITY, "dfoptional/" + SearchManager.SUGGEST_URI_PATH_QUERY + "/*", 0);

			// 點擊提示
			matcher.addURI(AUTHORITY, "item/#", 3);

			return matcher;
		}

		@Override
		public boolean onCreate() {
			suggestDao = new SuggestDao(getContext());
			return true;
		}

		/*
		* 當系統向你的Content Provider請求suggestion的時候,它將調用你的Content Provider的query()方法
		* */
		@Nullable
		@Override
		public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

			Log.d(TAG, "uri = "+ uri);
			Log.d(TAG, "projection =" + projection +",selection =" + selection);
			//若是在searchable配置文件設置了android:searchSuggestSelection屬性的話,
			// query text就以作爲selectionArgs字符串數組的第一個元素的形式傳過來.
			if(selectionArgs != null){
				Log.d(TAG, "selectionArgs[0]=" + selectionArgs[0] + ", sortOrder =" + sortOrder);
			}
			/*
			* 搜索提示:
			* uri = content://com.df.searchview.MyCustomSuggestionProvider/dfoptional/search_suggest_query?limit=50
			* (結構:content:// searchSuggestAuthority / searchSuggestPath / search_suggest_query )
			* projection =null,selection = ?
			* selectionArgs=呃, sortOrder =null
			*
			* 查詢:
			* uri = content://com.df.searchview.MyCustomSuggestionProvider/suggest
			*
			* 提示item點擊
			* uri = content://com.df.searchview.MyCustomSuggestionProvider/item/2
			*/

			String query = uri.getLastPathSegment().toLowerCase();
			Log.d(TAG, "query=" + query);

			switch (uriMatcher.match(uri)){
				case 0:
					// 查詢建議列表
					return getSuggestions(selectionArgs[0]);
				case 1:
					// 獲取所選單詞
					return getWord(uri);
				case 3:
					// 獲取所選單詞
					return getWord(uri);
				default:
					throw new IllegalArgumentException("Unknown Uri: " + uri);
			}
		}

二、編輯配置文件

1) AndroidManifest.xml
	
		<!--自定義搜索提示-->
		<provider
			android:name=".MyCustomSuggestionProvider"
			android:authorities="com.df.searchview.MyCustomSuggestionProvider"
			/>
	
	2) searchable.xml
	
		<searchable xmlns:android="http://schemas.android.com/apk/res/android"
			android:label="@string/app_name"
			android:hint="@string/search_hint"
			android:icon="@mipmap/icon"
			android:searchSuggestAuthority="com.df.searchview.MyCustomSuggestionProvider"
			android:searchSuggestPath="dfoptional"
			android:searchSuggestIntentAction="android.intent.action.VIEW"
			android:searchSuggestSelection="word MATCH ?"
			android:searchSuggestIntentData="content://com.df.searchview.MyCustomSuggestionProvider/item"
			>

		</searchable>

二、在SearchResultsActivity中處理

private void handleIntent(Intent intent) {

			String intentAction = intent.getAction();
			Log.d(TAG, "=IntentAction = " + intentAction);

			if (Intent.ACTION_SEARCH.equals(intentAction)) {
				String query = intent.getStringExtra(SearchManager.QUERY);
				Log.d(TAG,  "=query=" + query);

				// 自定義搜索記錄
				showResults(query);

				// 系統保存搜索記錄
				//SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
				//		MySuggestionProvider.AUTHORITY, MySuggestionProvider.MODE);
				//suggestions.saveRecentQuery(query, null); // 保存最近的數據
			} else if(Intent.ACTION_VIEW.equals(intentAction)){
				// 點擊搜索提示的條目
				Uri data = intent.getData();
				Intent wordIntent = new Intent(this, WordActivity.class);
				wordIntent.setData(data);
				startActivity(wordIntent);
			}
		}
		
		private void showResults(String query) {

			Log.d(TAG, "=======showResults========");

			Cursor cursor =  getContentResolver().query(MyCustomSuggestionProvider.CONTENT_URI, null, null,
					new String[] {query}, null);
			//Cursor cursor = managedQuery(MyCustomSuggestionProvider.CONTENT_URI, null, null,
			//		new String[] {query}, null);

			if (cursor == null) {
				// 沒結果
				mTextView.setText(getString(R.string.no_results, new Object[] {query}));
			} else {
				// 顯示結果
				int count = cursor.getCount();
				String countString = getResources().getQuantityString(R.plurals.search_results,
						count, count, query);
				mTextView.setText(countString);

				// 指定想顯示的列
				String[] from = new String[] { SuggestDao.COLUMN_TEXT1, SuggestDao.COLUMN_TEXT2 };

				// 對應控件
				int[] to = new int[] { R.id.word, R.id.definition };

				// 填充數據
				SimpleCursorAdapter wordAdapter = new SimpleCursorAdapter(this, R.layout.result, cursor, from, to);
				mListView.setAdapter(wordAdapter);

				// 單擊
				mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

						Log.d(TAG, "id = " + id);
						Intent wordIntent = new Intent(getApplicationContext(), WordActivity.class);
						Uri data = Uri.withAppendedPath(MyCustomSuggestionProvider.CONTENT_URI,
								String.valueOf(id));
						wordIntent.setData(data);
						startActivity(wordIntent);
					}
				});
			}
		}

參考:

官方文檔
    https://developer.android.com/guide/topics/search/search-dialog.html
    http://blog.csdn.net/hudashi/article/details/7052815(中文)

    搜索配置文件
    http://blog.csdn.net/suichukexun/article/details/7590732

    android (MD)v7.widget.SearchView的使用解析。
    https://zhuanlan.zhihu.com/p/22388833

    Android API指南(二)Search篇(待看)
    http://wangkuiwu.github.io/2014/06/17/Search/

Demo參考:

googleDemo:android-sdk\samples\android-23\legacy\SearchableDictionary
相關文章
相關標籤/搜索