Articles → Android → Search Functionality Using SearchView In Android
Search Functionality Using SearchView In Android
What Is SearchView?
Example
- Add a listbox in layout file. The purpose of this listbox is to display the list of items.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".debug.Demo">
<ListView android:id="@+id/lView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
- Add a menu folder. For that
- Right-click on res folder
- Go to New → Android Resource Directory
Click to Enlarge
- A popup will appear, where we can select a folder of type menu
Click to Enlarge- Once you click on Ok, a menu folder is created inside the res folder.
Click to Enlarge
- Add a resource file in the menu folder. For that
- Right-click on menu folder.
- Click on New → Menu Resource File.
Click to Enlarge
- A pop up window will appear where you can give the file name and click on Ok.
Click to Enlarge
- Add code in search_option.xml.
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/search" android:title="Search" app:showAsAction="always"
app:actionViewClass="android.widget.SearchView" />
</menu>
- Add a code on onCreate method to bind listbox with data source.
String fruitlist[] = {
"apple",
"banana",
"orange",
"cherry"
};
ListView listView = (ListView) findViewById(R.id.lView);
adapter = new ArrayAdapter < String > (this, R.layout.support_simple_spinner_dropdown_item, fruitlist);
listView.setAdapter(adapter);
- Override onCreateOptionsMenu and add a code to filter data
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search_option, menu);
MenuItem item = menu.findItem(R.id.search);
SearchView searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
adapter.getFilter().filter(s);
return false;
}
});
return true;
}
Output
Click to Enlarge
Click to Enlarge