這很簡單。您只需要使用Google的搜索功能,以便當用戶長按菜單按鈕時,它會加載一個搜索文本框,您可以在其中輸入搜索查詢以在您的應用程序中進行搜索。
可搜索的應用程序文件必須包含該元素作爲根節點並指定一個或多個屬性。 e.g
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/app_label"
android:hint="@string/search_hint" >
</searchable>
然後宣佈任何活動接受ACTION_SEARCH即
<application ... >
<activity android:name=".SearchableActivity" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="@xml/searchable"/>
</activity>
</application>
現在,我們需要控制查詢以及它是如何執行。 我用這個爲我的應用程序。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
// Get the intent, verify the action and get the query
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
doMySearch(query);
}
}
android androidsearch
好吧,但如果我使用ListFragment,那麼我將不必使用SearchView。我可以使用EditText和OnKeyListener來獲得相同的效果。問題是,如果有一種方法可以掛鉤到SearchView並使用其建議機制和UI,但是可以通過自定義的方式從我想要的任何源獲取建議,而不一定是內容提供者。 – user940016
只需製作您自己的ContentProvider即可返回您想要的數據(不一定是數據庫)。 這或子類SearchView並重新編寫適當的方法接受來自你想要的數據並適當地顯示它(你可能需要看看源代碼,看看它是如何完成的) – bennettaur
好吧,但那麼怎麼樣可搜索的活動?我不想使用它,但我必須定義它。我可以建立一個虛擬活動,但並不真正顯示嗎? – user940016