10

Background

I have a searchView being initialized using a special class I've made, that's being used across all of the activities and fragments.

The problem

Recently, probably due to updates to the support library (or because I didn't use it so far, I don't remember), I can't catch events of expand/collapse of the searchView.

As I've found, this happens even if I use setSupportActionBar with a Toolbar instance.

What I've tried

I've tried using each of the next methods, but none worked:

  • MenuItemCompat.setOnActionExpandListener.
  • MenuItemCompat.setOnActionExpandListener together with iconifying the SearchView, as suggested on some websites.
  • setOnActionExpandListener on the search menu item itself, but then it crashes since it can't be used when extending the ActionBarActivity.
  • SearchView.setOnCloseListener , but this works only if I close it, and only using the UI (doesn't get called when calling collapseActionView ).
  • I've also tried to mess around with the XML file of the search menu item.

The code

Here's the helper class I've made:

SearchHolderCompat

public class SearchHolderCompat {
    public MenuItem mSearchMenuItem;
    public SearchView mSearchView;
    private final Activity _context;

    public SearchHolderCompat(final Activity context) {
        _context = context;
    }

    public boolean isCurrentyExpanded() {
        return mSearchMenuItem != null && MenuItemCompat.isActionViewExpanded(mSearchMenuItem);
    }

    public boolean hasQuery() {
        return mSearchMenuItem != null && mSearchView != null && MenuItemCompat.isActionViewExpanded(mSearchMenuItem)
                && !TextUtils.isEmpty(mSearchView.getQuery());
    }

    public void addSearchItemAndInit(final Menu menu, final OnQueryTextListener onQueryTextListener,
            final OnActionExpandListener onActionExpandListener) {
        final MenuInflater menuInflater = _context.getMenuInflater();
        menuInflater.inflate(R.menu.search_menu_item, menu);
        init(menu.findItem(R.id.menuItem_search), onQueryTextListener, onActionExpandListener);
    }

    public void init(final MenuItem searchMenuItem, final OnQueryTextListener onQueryTextListener,
            final OnActionExpandListener onActionExpandListener) {
        this.mSearchMenuItem = searchMenuItem;
        mSearchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem);
        if (mSearchView == null) {
            MenuItemCompat.setShowAsAction(searchMenuItem, MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
                    | MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
            MenuItemCompat.setActionView(searchMenuItem, mSearchView = new SearchView(_context));
        }
        mSearchView.setQueryHint(_context.getString(R.string.search));
        mSearchView.setOnQueryTextListener(onQueryTextListener);
        MenuItemCompat.setOnActionExpandListener(searchMenuItem, onActionExpandListener);
    }

}

MainActivity.java

public class MainActivity extends ActionBarActivity {
    SearchHolderCompat mSearchHolder = new SearchHolderCompat(this);

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        mSearchHolder.addSearchItemAndInit(menu, new OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(final String arg0) {
                android.util.Log.d("AppLog", "onQueryTextSubmit");
                return false;
            }

            @Override
            public boolean onQueryTextChange(final String queryText) {
                android.util.Log.d("AppLog", "onQueryTextChange");
                return true;
            }
        }, new OnActionExpandListener() {

            @Override
            public boolean onMenuItemActionExpand(final MenuItem arg0) {
                android.util.Log.d("AppLog", "onMenuItemActionExpand");
                return false;
            }

            @Override
            public boolean onMenuItemActionCollapse(final MenuItem arg0) {
                android.util.Log.d("AppLog", "onMenuItemActionCollapse");
                return false;
            }
        });
        return true;
    }
}

search_menu_item.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto" >

    <!-- search items -->
    <item
        android:id="@+id/menuItem_search"
        android:icon="@drawable/ic_action_search"
        android:title="@string/search"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="always"
        tools:ignore="AlwaysShowAction"/>

</menu>

The question

What's the correct way to handle the SearchView and the search menu item (using the support library) ?

How come "MenuItemCompat.setOnActionExpandListener" doesn't work?

android developer
  • 114,585
  • 152
  • 739
  • 1,270
  • whats your device api level? – pskink Dec 14 '14 at 12:38
  • also is your `MenuItem item` an instance of android.support.v4.internal.view.SupportMenuItem ? see: http://androidxref.com/5.0.0_r2/xref/frameworks/support/v4/java/android/support/v4/view/MenuItemCompat.java#433 – pskink Dec 14 '14 at 12:46
  • 1
    @pskink SupportMenuItem is an interface. You can't create a new instance of it... About device API level, it's using the support library v7, so it should work from API7. However, the app's minSdk is 14 (ICS). I'd like to know the solution for all versions though. The official solution for the support library. The reason is that ActionBarActivity provides more than just supporting pre-Honeycomb devices. – android developer Dec 14 '14 at 12:50
  • i know its interface, does your item implement it? – pskink Dec 14 '14 at 12:51
  • 1
    @pskink I don't create it. It's the framework that's responsible of doing it. I just pass it using "menu.findItem" . Even if you add it by yourself, you get the MenuItem of Android framework. – android developer Dec 14 '14 at 12:53
  • just Log.d item.getClass() – pskink Dec 14 '14 at 12:54
  • 1
    @pskink This is the class of the menu item : "android.support.v7.internal.view.menu.MenuItemImpl" . – android developer Dec 14 '14 at 12:56
  • try to change app:showAsAction="always|collapseActionView", (Notice that the showAsAction attribute also includes the "collapseActionView" value. This is optional and declares that the action view should be collapsed into a button.) – pskink Dec 14 '14 at 13:07
  • did it do the trick? – pskink Dec 14 '14 at 13:17
  • @pskink No, this is one of the things I've tried. For some reason, it calls "onMenuItemActionExpand" , but doesn't really expand anything. It just stays as a button . EDIT: now that I've also set the listener to return true, it works fine. Odd that I didn't try this combination. I've tried many other combinations... If you wish, you can put this as an answer and I will mark it as the correct one. – android developer Dec 14 '14 at 13:57
  • I answered the question here: http://stackoverflow.com/a/28762632/1633609 – Sir NIkolay Cesar The First Feb 27 '15 at 10:18

4 Answers4

6

After looking for a solution for couple of hours I've implement something like this. and worked for me. (I wanted Expand and Collapse events anyhow)
.

@Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        MenuItem searchItem = menu.findItem(R.id.action_search);



        if(searchItem != null)
        {

            SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
            // use this method for search process
            searchView.setOnSearchClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    //Search view is expanded
                    showSearchPage();
                }
            });
            searchView.setOnCloseListener(new SearchView.OnCloseListener()
            {
                @Override
                public boolean onClose()
                {
                    //Search View is collapsed
                    hideSearchPage();
                    return false;
                }
            });
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
            {

                @Override
                public boolean onQueryTextSubmit(String query)
                {
                    // use this method when query submitted
                    Toast.makeText(MainActivity.this, query, Toast.LENGTH_SHORT).show();
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText)
                {
                    // use this method for auto complete search process
                    Log.e("SearchValueIs",":"+newText);
                    return false;
                }
            });
        }
        return super.onCreateOptionsMenu(menu);
    }


Hope It will help Someone...

GreenROBO
  • 4,725
  • 4
  • 23
  • 43
5

Android training

app:showAsAction="ifRoom|collapseActionView"
txbnx
  • 51
  • 1
  • 2
1

You can add ViewTreeObserver to track the visibility state of android.support.v7.appcompat.R.id.search_edit_frame. You can check my answer here: https://stackoverflow.com/a/28762632/1633609

You can see below how to handle Expand and Collapsed states!

To answer why MenuItemCompat.setOnActionExpandListener(...) is not working, this listener is only called if the showAsAction of the SearchView is set to MenuItemCompat.SHOW_AS_ACTION_ALWAYS (you can also add more options).

This is the copy of my answer form the other question:

I found that MenuItemCompat.setOnActionExpandListener(...) is not working if you don't pass:

    searchItem
            .setShowAsAction(MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
                    | MenuItemCompat.SHOW_AS_ACTION_ALWAYS);

But this is changing the SearchView and is replacing the DrawerToggle with back arrow.

I wanted to keep the original views and still track the Expanded/Collapsed state and use supported Search View.

Solution:

When android.support.v7.widget.SearchView is changing the view state the LinearLayout view's, with id android.support.v7.appcompat.R.id.search_edit_frame, visibility value is being changed from View.VISIBLE to View.GONE and opposite. So I add ViewTreeObserver to track the visibility change of the search edit frame.

menu_search.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >

<item
    android:id="@+id/action_search"
    android:icon="@android:drawable/ic_menu_search"
    android:title="@string/search"
    app:actionViewClass="android.support.v7.widget.SearchView"
    app:showAsAction="always"/>

</menu>

In the activity:

import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;

..........

private View mSearchEditFrame;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_search, menu);
    MenuItem searchItem = (MenuItem) menu.findItem(R.id.action_search);

    SearchView searchView = (SearchView) MenuItemCompat
            .getActionView(searchItem);
    searchView.setSubmitButtonEnabled(false);
    mSearchEditFrame = searchView
            .findViewById(android.support.v7.appcompat.R.id.search_edit_frame);

    ViewTreeObserver vto = mSearchEditFrame.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        int oldVisibility = -1;

        @Override
        public void onGlobalLayout() {

            int currentVisibility = mSearchEditFrame.getVisibility();

            if (currentVisibility != oldVisibility) {
                if (currentVisibility == View.VISIBLE) {
                    Log.v(TAG, "EXPANDED");
                } else {
                    Log.v(TAG, "COLLAPSED");
                }

                oldVisibility = currentVisibility;
            }

        }
    });

    return super.onCreateOptionsMenu(menu);
}
Community
  • 1
  • 1
0

I know I'm very late to post this answer but hope it helps someone else. I recently came across the issue and I just made the Override methods return true and it worked like a charm.

        @Override
        public boolean onMenuItemActionExpand(final MenuItem arg0) {

            android.util.Log.d("AppLog", "onMenuItemActionExpand");
            return true;
        }

        @Override
        public boolean onMenuItemActionCollapse(final MenuItem arg0) {

            android.util.Log.d("AppLog", "onMenuItemActionCollapse");
            return true;
        }

In more recent versions

      menuSearch.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
        @Override
        public boolean onMenuItemActionExpand(MenuItem item) {

            //SearchView appers
            return true;
        }

        @Override
        public boolean onMenuItemActionCollapse(MenuItem item) {

            //SearchView disappears
            return true;
        }
    });
Skylark
  • 103
  • 1
  • 8