Search code examples
androidandroid-support-librarysearchviewandroid-actionbar-compatandroid-actionbaractivity

How to support searchItem.setOnActionExpandListener in API level 8+?


I am using ActionBarActivity ,How to support searchItem.setOnActionExpandListener in API level 8+ ? It says that minimum API level 14 is required for this.

Below is the my code, Currently I’m suppressing the error and allowing the code execution only if the API is >=14 .

@SuppressLint("NewApi")
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.action_bar_home_screen, menu);
    searchItem = menu.findItem(R.id.action_search);
    SearchView searchView = (SearchView) MenuItemCompat
                .getActionView(searchItem);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            searchItem.setOnActionExpandListener(new OnActionExpandListener() {

                @Override
                public boolean onMenuItemActionExpand(MenuItem item) {
                    hideProgressBar();
                    return true;
                }

                @Override
                public boolean onMenuItemActionCollapse(MenuItem item) {
                    showProgressBar();
                    selectItem(lastSelectedItemPosition);
                    return true;
                }
            });
        }
}

Solution

  • Use MenuItemCompat.setOnActionExpandListener, which is the backport of OnActionExpandedListener.