我按照 http://developer.android.com/guide/topics/search/search-dialog.html 中描述的步骤进行操作在我的记事本应用程序中实现搜索功能。
我的问题是,当我完成搜索时,会打开一个新 Activity 来捕获我的搜索查询。但我真正想要的是将查询返回到当前 Activity ,而不是开始一个新 Activity 。
这可能吗?
更新:
AndroidManifest.xml
<activity android:name="MyNotepad"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.SEARCH"></action>
</intent-filter>
<meta-data android:resource="@xml/searchable" android:name="android.app.searchable"></meta-data>
</activity><activity android:name="Preferences" android:label="Preferences" >
</activity>
可搜索的.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">
</searchable>
JAVA代码
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_pad);
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
Toast.makeText(getApplicationContext(), query, Toast.LENGTH_LONG).show();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.menuItemSearch:
startSearch("", false, null, false);
break;
}
return true;
}
即使我使用手机上的搜索按钮,它也不起作用。因此,我认为问题出在 AndroidManifest.xml
最佳答案
在您的应用程序 list 中,您需要将当前 Activity 定义为可搜索 Activity 。
<activity android:name="BrowseItems" android:label="@string/browseitems"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="@xml/itemsearchable" />
</activity>
然后您使用以下代码,它来自 http://developer.android.com/guide/topics/search/search-dialog.html#LifeCycle
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
handleIntent(getIntent());
}
@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);
// Do work using string
}
}
然后您可以使用字符串重新加载您的 Activity ,如果它是一个列表 Activity ,您可以调用您用来加载数据的代码并在其中使用字符串。
关于Android:将搜索查询返回到当前 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5094222/