Android SearchView: Simple Search Function Guide
To implement a simple search function, you can use the SearchView widget and SearchManager class provided in Android. Below are the steps for a simple implementation.
- Add a SearchView widget to the layout file.
<SearchView
android:id="@+id/searchView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:iconifiedByDefault="false"
android:queryHint="Search Here"/>
- Obtain the SearchView widget in the Activity and set up the relevant listeners.
SearchView searchView = findViewById(R.id.searchView);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
// 处理搜索提交事件
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
// 处理搜索文本变化事件
return false;
}
});
- Handle the search submit event in the onQueryTextSubmit method, where you can perform the search operation and update the UI to display the results.
- In the onQueryTextChange method, handle the event of the search text changing, where you can search in real time and update the search results.
- Enable the search functionality for Activity in the AndroidManifest.xml file.
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable"/>
</activity>
- Create an XML file (such as searchable.xml) to define search configuration information.
<?xml version="1.0" encoding="utf-8"?>
<searchable
xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/app_name"
android:hint="Search Here"/>
By following the above steps, a simple search function can be implemented. When a user enters a search keyword in the SearchView, the search can be conducted based on the keyword and the search results can be displayed on the UI.