Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1
Using SearchView

Next, create a new menu XML file for PhotoGalleryFragment in res/menu/
fragment_photo_gallery.xml. This file will specify the items that should appear in the toolbar.


Listing 27.6  Adding menu XML file
(res/menu/fragment_photo_gallery.xml)


<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">


<item android:id="@+id/menu_item_search"
android:title="@string/search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom" />


<item android:id="@+id/menu_item_clear"
android:title="@string/clear_search"
app:showAsAction="never" />



You will see a couple of errors in the new XML, complaining that you have not yet defined the strings
you are referencing for the android:title attributes. Ignore those for now. You will fix them in a bit.


The first item entry in Listing 27.6 tells the toolbar to display a SearchView by specifying the value
android.support.v7.widget.SearchView for the app:actionViewClass attribute. (Notice the usage
of the app namespace for the showAsAction and actionViewClass attributes. Refer back to Chapter 13
if you are unsure of why this is used.)


SearchView (android.widget.SearchView) was originally introduced long ago in API 11
(Honeycomb 3.0). However, SearchView was more recently included as part of the support library
(android.support.v7.widget.SearchView). So which version of SearchView should you use? You
have seen our answer in the code you just entered: the support library version. This may seem strange,
as your app’s minimum SDK is 19.


We recommend using the support library for the same reasons outlined in Chapter 7. As features get
added with each new release of Android, the features are often back-ported to the support library.
A prime example is theming. With the release of API 21 (Lollipop 5.0), the native framework
SearchView supports many options for customizing the SearchView’s appearance. The only way to get
these fancy features on earlier versions of Android (down to API 7) is to use the support library version
of SearchView.


The second item in Listing 27.6 will add a Clear Search option. This option will always display in the
overflow menu because you set app:showAsAction to never. Later on you will configure this item so
that, when pressed, the user’s stored query will be erased from the disk. For now, you can ignore this
item.


Now it is time to address the errors in your menu XML. Open strings.xml and add the missing
strings.


Listing 27.7  Adding search strings (res/values/strings.xml)



...
Search
Clear Search
Free download pdf