Search code examples
androidandroid-actionbarandroid-support-libraryandroid-search

Android use support library to support SearchView


This is my code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    MenuItem searchItem = menu.findItem(R.id.searchMenuItem);
    SearchManager searchManager =
        (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
    // searchView.set
    searchView.setSearchableInfo(
        searchManager.getSearchableInfo(getComponentName()));
    searchView.setIconifiedByDefault(false);
}

My minimum API is 8.
I have this compile error

Call requires API level 11 (current min is 8):
    android.widget.SearchView#setSearchableInfo

Note, that I can't change the minimum SDK.


Solution

  • You can use android.support.v7.widget.SearchView

    instead of android.widget.SearchView

    Your code could look like this:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    MenuItem searchItem = menu.findItem(R.id.searchMenuItem);
                    SearchManager searchManager =
                            (SearchManager) getSystemService(Context.SEARCH_SERVICE);
                    android.support.v7.widget.SearchView searchView = (android.support.v7.widget.SearchView) MenuItemCompat.getActionView(searchItem);
    
                    searchView.setSearchableInfo(
                            searchManager.getSearchableInfo(getComponentName()));
                    searchView.setIconifiedByDefault(false);
    
                }
    

    Also please read more about SearchViewCompat