Android 搜索框 search dialog 和 search widget

分为search dialog和search widget

区别:

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基础##

原理:

当用户在search dialog或search widget中执行一个搜索的时候,系统会创建一个Intent,并把查询关键字保存在里面,然后启动我们在AndroidManifest.xml中声明好的searchable activity,并把Intent传送给它。

步骤:

1、res/menu 目录下 创建menu资源文件 menu_main.xml

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

2、重写onCreateOptionsMenu方法

	[@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); // 是否显示提交按钮
	}

3、创建处理搜索的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>

4、创建res/xml/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"
	>

	</searchable>

5、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);

6、在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 最近搜索提示##

1、创建搜索提示的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);
		}
	}

2、配置manifest

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

3、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);  // 保存最近的数据
		}
	}

4、配置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>

5、清除查询数据

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

##search dialog 自定义Suggestions##

1、创建自定义内容提供者

	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);
			}
		}

2、编辑配置文件

	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>

2、在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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值