public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case LOCAL_SEARCH_ID:
onSearchRequested();
return(true);
case GLOBAL_SEARCH_ID:
startSearch (null, false, null, true);
return(true);
case CLOSE_ID:
finish();
return(true);
}
return(super.onOptionsItemSelected (item));
}
}
This activity takes care of everything related to showing a list of words, even loading the words out of the XML resource. What it does not do is come up with the ListAdapter
to put into the ListView
— that is delegated to the subclasses.
The main activity — LoremDemo
— just uses a ListAdapter
for the whole word list:
package com.commonsware.android.search;
import android.content.Intent;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
public class LoremDemo extends LoremBase {
@Override ListAdapter makeMeAnAdapter(Intent intent) {
return(new ArrayAdapter<String> (this,
android.R.layout.simple_list_item_1, items));
}
}
The search activity, though, does things a bit differently. First, it inspects the Intent
supplied to the abstract makeMeAnAdapter()
method. That Intent comes from either onCreate()
or onNewIntent()
. If the intent is an ACTION_SEARCH
, then we know this is a search. We can get the search query and, in the case of this silly demo, spin through the loaded list of words and find only those containing the search string. That list then gets wrapped in a ListAdapter
and returned for display:
package com.commonsware.android.search;
import android.app.SearchManager;
import android.content.Intent;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import java.util.ArrayList;
import java.util.List;
public class LoremSearch extends LoremBase {
@Override
ListAdapter makeMeAnAdapter(Intent intent) {
ListAdapter adapter = null;
if (intent.getAction().equals (Intent.ACTION_SEARCH)) {
String query = intent.getStringExtra(SearchManager.QUERY);
List<String> results = searchItems(query);
adapter = new ArrayAdapter<String> (this,
android.R.layout.simple_list_item_1, results);
setTitle('LoremSearch for: ' + query);
}
return(adapter);
}
private List<String> searchItems(String query) {
List<String> results = new ArrayList<String>();
for (String item : items) {
if (item.indexOf(query) - 1) {
results.add(item);
}
}
return(results);
}
}
Update the Manifest
While this implements search, it doesn’t tie it into the Android search system. That requires a few changes to the auto-generated AndroidManifest.xml
file:
<manifest xmlns:android='http://schemas.android.com/apk/res/android'
package='com.commonsware.android.search'>
<application>
<activity android:name='.LoremDemo' android:label='LoremDemo'>
<intent-filter>
<action android:name='android.intent.action.MAIN' />