Keywords: Android | SearchView | Auto-completion | Action Bar | Adapter
Abstract: This article provides a comprehensive guide on integrating SearchView into the Android action bar and implementing auto-completion suggestions based on string arrays. It covers step-by-step configuration, adapter implementation, and event handling, drawing from high-scoring Stack Overflow answers to ensure accuracy. The content includes full code examples and best practices for data binding and UI optimization, making it a practical resource for developers.
Introduction
In Android app development, SearchView is a common component in the action bar that allows users to input queries and receive real-time suggestions. However, when the data source is an ArrayList<String>, implementing auto-completion can be challenging. Based on high-scoring Stack Overflow answers, this article explores how to configure SearchView to display auto-completion suggestions from string arrays, with complete code examples and best practices.
Basic Configuration of SearchView
First, define the SearchView in a menu resource file. Create an XML file, e.g., res/menu/example.xml, and add the following:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/search"
android:title="@string/search"
android:showAsAction="ifRoom"
android:actionViewClass="android.widget.SearchView" />
</menu>In the activity, load this menu via the onCreateOptionsMenu method. For Android X or support library versions, it is recommended to use app:showAsAction and app:actionViewClass attributes, such as app:actionViewClass="androidx.appcompat.widget.SearchView", to ensure compatibility.
Data Source and Adapter Implementation
Assume a string list items as the data source. In onCreateOptionsMenu, initialize the SearchView and set a query listener:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.example, menu);
SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView search = (SearchView) menu.findItem(R.id.search).getActionView();
search.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextChange(String query) {
loadHistory(query);
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
});
return true;
}In the loadHistory method, convert the string array to a MatrixCursor for the adapter. When creating the MatrixCursor, define columns such as _id and text, and iterate through the items list to add rows:
private void loadHistory(String query) {
String[] columns = new String[] { "_id", "text" };
MatrixCursor cursor = new MatrixCursor(columns);
for (int i = 0; i < items.size(); i++) {
cursor.addRow(new Object[] { i, items.get(i) });
}
SearchView search = (SearchView) menu.findItem(R.id.search).getActionView();
search.setSuggestionsAdapter(new ExampleAdapter(this, cursor, items));
}Next, implement a custom adapter ExampleAdapter, extending android.widget.CursorAdapter. In the adapter, override the newView and bindView methods to bind data to views:
public class ExampleAdapter extends CursorAdapter {
private List<String> items;
public ExampleAdapter(Context context, Cursor cursor, List<String> items) {
super(context, cursor, false);
this.items = items;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
return inflater.inflate(R.layout.item, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView text = view.findViewById(R.id.text);
text.setText(items.get(cursor.getPosition()));
}
}The layout file res/layout/item.xml should include a TextView to display suggestion items.
Configuration and Optimization
To complete the functionality, configure search intents and metadata in AndroidManifest.xml:
<activity android:name=".ExampleActivity">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.default_searchable"
android:value=".ExampleActivity" />
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
</activity>Create a res/xml/searchable.xml file to define search properties, such as label and hint text. Additionally, consider performance optimization: if data comes from a database, use a Cursor directly instead of MatrixCursor to reduce memory overhead.
Common Issues and Solutions
During implementation, developers may encounter null pointer exceptions or compatibility issues. For example, when using Android X, ensure menu item attributes are correct, such as app:actionViewClass="androidx.appcompat.widget.SearchView". Also, the adapter should avoid importing the support library version of CursorAdapter and instead use the standard android.widget.CursorAdapter. Testing across different Android versions can ensure stability and consistency.
Conclusion
This article details the process of implementing SearchView auto-completion in the Android action bar, from basic configuration to advanced adapter design. By combining string array data sources with custom adapters, developers can create responsive and user-friendly search interfaces. Referencing Stack Overflow solutions, this article provides validated code examples to help developers quickly integrate and optimize search functionality in their apps.