The Open Event Android App has a map for showing all locations of sessions. All the locations have a marker in the map. It is difficult to find a particular location on the map because to know the name of location user has to click on the marker. Adding autocomplete SearchView will improve user experience by providing an ability to search the location by name and by suggesting name according to the search query. In this post I explain how to add autocomplete SearchView in the fragment or activity.
Add search icon in actionbar
The first step to do is to create a menu xml file and add a search menu item in it. Then inflate this menu xml file in Fragment in onCreateOptionsMenu() method.
1. Create menu.xml file
In this file add search menu element. Inside menu element add search menu item. Define id, title, and icon of search menu item. Add android.support.v7.widget.SearchView” as actionViewClass which will be used as action view when the user clicks on the icon.
2. Inflate menu.xml file in Fragment
In the fragment’s onCreateOptionsMenu() method inflate menu.xml file using MenuInflater’s inflate() method. Then find search menu item using menu’s findItem() method by passing id of search menu item as parameter.
Add and initialize SearchView
Now after adding search icon we need to add SearchView and SearchAutoComplete fields in the fragment.
Initialize SearchView in onCreateOptionMenu() method by passing search menu item in the getActionView() method of MenuItemCompat.
Here SearchAutoComplete is a child object of SearchView so initialize it using findViewById method of SearchView by passing the id as parameter.
Define properties of SearchAutoCompleteView
By default background of drop down menu in SearchAutoComplete is black. You can change background using setDropDownBackgroundResource() method. Here i’m making it white by providing white drawable resource.
The setDropDownAnchor() method sets the view to which the auto-complete drop down list should anchor. The setThreshold() method specifies the minimum number of characters the user has to type in the edit box before the drop down list is shown.
Create array adapter
Now it’s time to make the ArrayAdapter object which will provide the data set (strings) which will be used to run search queries.
Here searchItems is List of strings. Now set this adapter to the mSearchAutoComplete object using setAdapter() method.
Now we are all set to run the app on device or emulator. Here’s demo how it will look
The SearchView with an ability to give suggestions serves the great user experience in the application.
- SearchView : https://developer.android.com/reference/android/support/v7/widget/SearchView.html
- AutoCompleteTextView Tutorial : https://www.tutorialspoint.com/android/android_auto_complete.htm
- Open Event Android PR : https://github.com/fossasia/open-event-android/pull/1749