我正在尝试创建我的第一个 Android 应用程序,并正在添加搜索功能。我已经按照 Android 开发者文档添加了搜索对话框和小部件。不幸的是,每当我执行搜索时,都会调用搜索活动的“onCreate”和“onNewIntent”。也就是说,通过在操作栏搜索框中键入内容并按 ENTER,搜索称为 TWICE。我被困住了。是否应该从 Searchable 活动返回一些全局标志,通知应用程序搜索已完成?搜索对话框和小部件都被调用了吗?
我在这个网站和网络上搜索过以前的帖子,但无济于事。感谢您的任何帮助。
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.shop"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<service android:name="com.shop.RestIntentService" />
<activity
android:name="com.shop.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.shop.CatalogActivity"
android:label="@string/app_name" >
</activity>
<activity
android:name="com.shop.SearchableActivity"
android:launchMode="singleTop" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<!--
<intent-filter>
<action android:name="android.intent.action.VIEW" />
</intent-filter>
-->
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
</activity>
<meta-data
android:name="android.app.default_searchable"
android:value="com.shop.SearchableActivity" />
</application>
</manifest>
SearchableActivity.java
public class SearchableActivity extends ListActivity implements Receiver {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("onCreate");
handleIntent(getIntent());
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
System.out.println("onNewIntent");
setIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
doSearch(query);
}
}
private void doSearch(String queryStr) {
System.out.println("searching..." + queryStr);
}
目录活动.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.sample, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
//return super.onCreateOptionsMenu(menu);
return true;
}
示例.xml
<item
android:id="@+id/menu_search"
android:actionViewClass="android.widget.SearchView"
android:icon="@android:drawable/ic_menu_search"
android:showAsAction="ifRoom|collapseActionView"
android:title="@string/menu_search"/>