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.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.search:
            onSearchRequested();
            return true;
        default:
            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.

@Override
public boolean onCreateOptionsMenu(Menu menu) {

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

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        SearchManager searchManager =
                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView =
                (SearchView) menu.findItem(R.id.search).getActionView();
        searchView.setSearchableInfo(
                searchManager.getSearchableInfo(getComponentName()));
        searchView.setIconifiedByDefault(false);
    }
    return true;
}

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