Android使用支持库来支持SearchView

时间:2014-02-17 07:02:55

标签: android android-actionbar android-support-library android-search

这是我的代码:

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);
}

我的最低API是8 我有这个编译错误

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

请注意,我无法更改最低SDK。

1 个答案:

答案 0 :(得分:9)

你可以使用 android.support.v7.widget.SearchView

而不是 android.widget.SearchView

您的代码可能如下所示:

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);

            }

另请阅读有关 SearchViewCompat

的更多信息