SearchView and backward compatibility

I was researching some things on the android website and I found this topic interesting as Backwards compatibility is an important factor in any software development. This tutorial is going to quickly show you how to allow backwards compatibility when using SearchView and the Action Bar which are only supported in Android 3.0 and above.

First, when decaring minimum and target API, you want to allow older device support but target for Android 3.0 or later.

<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="15" />

This allows you to let the system know that you want to allow older support but want to target for Android 3.0 if available. In contrast, if your device is using an Android version lower than 3.0 it will try to use the traditional menu system.

Next you also need to Provide a Search Dialog method for older devices. Whenever a user selects the search menu item, you have to call onSearchRequested(); for Action bars, you need to call onOptionsItemSelected() for when a search menu item is selected.

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
            return true;
            return false;

Lastly, you need to add some code to check the Android build version at runtime, which is done for you here overriding the onCreateOptionsMenu.

public boolean onCreateOptionsMenu(Menu menu) {

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(, menu);

        SearchManager searchManager =
                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView =
                (SearchView) menu.findItem(;
    return true;

This will allow you to make sure unsupported use of SearchView doesn’t occur.