当您需要在您的应用程序中提供搜索服务时,您第一个想到的是您的搜索框要放哪呢?通过使用
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;
}
对于以上有不明白指出,或者有错误指出,欢迎批评指正。