SearchView's OnCloseListener doesn't work

57,588

Solution 1

I also meet this problem, and I have no choice but give up "oncloselistener". Instead, you can get your menuItem, then setOnActionExpandListener. Then override unimplents methods.

@Override
public boolean onMenuItemActionExpand(MenuItem item) {
    // TODO Auto-generated method stub
    Log.d("*******","onMenuItemActionExpand");
    return true;
}

@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
    //do what you want to when close the sesarchview
    //remember to return true;
    Log.d("*******","onMenuItemActionCollapse");
    return true;
}

Solution 2

For Android API 14+ (ICS and greater) use this code:

// When using the support library, the setOnActionExpandListener() method is
// static and accepts the MenuItem object as an argument
MenuItemCompat.setOnActionExpandListener(menuItem, new OnActionExpandListener() {
    @Override
    public boolean onMenuItemActionCollapse(MenuItem item) {
        // Do something when collapsed
        return true;  // Return true to collapse action view
    }

    @Override
    public boolean onMenuItemActionExpand(MenuItem item) {
        // Do something when expanded
        return true;  // Return true to expand action view
    }
});

For more information: http://developer.android.com/guide/topics/ui/actionbar.html#ActionView

Ref: onActionCollapse/onActionExpand

Solution 3

For this problem I came up with something like this,

private SearchView mSearchView;

@TargetApi(14)
@Override
public boolean onCreateOptionsMenu(Menu menu)
{

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

    mSearchView = (SearchView) menu.findItem(R.id.itemSearch).getActionView();

    MenuItem menuItem = menu.findItem(R.id.itemSearch);

    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    {
        menuItem.setOnActionExpandListener(new OnActionExpandListener()
        {

            @Override
            public boolean onMenuItemActionCollapse(MenuItem item)
            {
                // Do something when collapsed
                Log.i(TAG, "onMenuItemActionCollapse " + item.getItemId());
                return true; // Return true to collapse action view
            }

            @Override
            public boolean onMenuItemActionExpand(MenuItem item)
            {
                // TODO Auto-generated method stub
                Log.i(TAG, "onMenuItemActionExpand " + item.getItemId());
                return true;
            }
        });
    } else
    {
        // do something for phones running an SDK before froyo
        mSearchView.setOnCloseListener(new OnCloseListener()
        {

            @Override
            public boolean onClose()
            {
                Log.i(TAG, "mSearchView on close ");
                // TODO Auto-generated method stub
                return false;
            }
        });
    }


    return super.onCreateOptionsMenu(menu);

}

Solution 4

I ran into same problem on android 4.1.1. Looks like it is a known bug: https://code.google.com/p/android/issues/detail?id=25758

Anyway, as a workaround i used state change listener (when SearchView is detached from action bar, it is also closed obviously).

view.addOnAttachStateChangeListener(new OnAttachStateChangeListener() {

    @Override
    public void onViewDetachedFromWindow(View arg0) {
        // search was detached/closed
    }

    @Override
    public void onViewAttachedToWindow(View arg0) {
        // search was opened
    }
});

Above code worked well in my case.


I post same answer here: https://stackoverflow.com/a/24573266/2162924

Solution 5

I ended up using a bit of a hack, that works well for my purpose - not sure it'll work with all purposes. Anyway, I'm doing a check to see if the search query is empty. This is not really related to the SearchView's OnCloseListener though - that still doesn't work!

searchView.setOnQueryTextListener(new OnQueryTextListener() {
            @Override
            public boolean onQueryTextChange(String newText) {
                if (newText.length() > 0) {
                    // Search
                } else {
                    // Do something when there's no input
                }
                return false;
            }
            @Override
            public boolean onQueryTextSubmit(String query) { return false; }
        });
Share:
57,588

Related videos on Youtube

Michell Bak
Author by

Michell Bak

I like Android. Android is good for me. And you.

Updated on July 14, 2022

Comments

  • Michell Bak
    Michell Bak almost 2 years

    I'm trying to add support for the SearchView in the Android 3.0+ ActionBar, but I can't get the OnCloseListener to work.

    Here's my code:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        searchView = (SearchView) menu.findItem(R.id.search_textbox).getActionView();
        searchView.setOnQueryTextListener(new OnQueryTextListener() {
            @Override
            public boolean onQueryTextChange(String newText) {
                searchLibrary(newText);
                return false;
            }
            @Override
            public boolean onQueryTextSubmit(String query) { return false; }
        });
        searchView.setOnCloseListener(new OnCloseListener() {
            @Override
            public boolean onClose() {
                System.out.println("Testing. 1, 2, 3...");
                return false;
            }
        });
        return true;
    }
    

    The search works great and every is working except for the OnCloseListener. Nothing is being printed to Logcat. Here's the Logcat for when I'm pressing the "Close" button:

    02-17 13:01:52.914: I/TextType(446): TextType = 0x0
    02-17 13:01:57.344: I/TextType(446): TextType = 0x0
    02-17 13:02:02.944: I/TextType(446): TextType = 0x0
    

    I've looked through the documentation and samples, but nothing seemed to change it. I'm running it on a Asus Transformer Prime and a Galaxy Nexus, both on Ice Cream Sandwich. Any ideas?

    Update:

    Yes - System.out.println() does work. Here's proof:

       @Override
     public boolean onQueryTextChange(String newText) {
        System.out.println(newText + "hello");
        searchLibrary(newText);
        return false;
     }
    

    Results in this Logcat:

    02-17 13:04:20.094: I/System.out(21152): hello
    02-17 13:04:24.914: I/System.out(21152): thello
    02-17 13:04:25.394: I/System.out(21152): tehello
    02-17 13:04:25.784: I/System.out(21152): teshello
    02-17 13:04:26.064: I/System.out(21152): testhello
    
    • PJL
      PJL about 12 years
      Hmm, Works OK for me with Android 3.2 but NOT for 4.0+
    • PJL
      PJL about 12 years
      Raised bug, 25758
    • bencallis
      bencallis about 12 years
      I'm glad it is not just me having this problem. Anyone have any other hacks other than the one below?
    • Beraki
      Beraki over 7 years
      I have learnt two things if showAsAction is set to always. Search box has a close button of its own but if it is set to ifRoom | collapseActionView it expands on the action bar.
  • Michell Bak
    Michell Bak about 12 years
    Not true, it works just fine. Please see my updated question - I've added a line in the onQueryTextChange method to prove it. Also tried adding Log.d(), but that didn't display anything either.
  • Chris Knight
    Chris Knight about 12 years
    Oh, my bad! Looks like somewhere along the way they've decided to output System.out.println to the Log.i. Good luck
  • Michell Bak
    Michell Bak about 12 years
    Hey Sparky, thanks for commenting on this. I don't really see how that should change anything. A nested listener is a valid way of making it as well, and it works on Honeycomb as you can see based on the comments here. I haven't had any issues with nested listeners on ICS other than this - which again works on Honeycomb.
  • Michell Bak
    Michell Bak about 12 years
    By nested listeners I mean anonymous inner classes.
  • Sparky
    Sparky about 12 years
    I agree that it shouldn't matter. I'm only commenting on what's present in the code base. I'll look and see if maybe the conditions in which onClose were redefined.
  • Joseph Earl
    Joseph Earl over 11 years
    I'm not sure you understand Java -- it's called an anonymous inner class.
  • NKijak
    NKijak over 11 years
    I believe we're only talking about ActionBar's SearchView which is only honeycomb+
  • Giuseppe
    Giuseppe over 11 years
    I just tried adding setIconifiedByDefault(true) but it is not called
  • Robert
    Robert over 10 years
    don't bother using onCloseListener, just use this one with your menu item.
  • Ripityom
    Ripityom over 10 years
    I think you can use MenuItemCompat.OnActionExpandListener for earlier API levels: developer.android.com/reference/android/support/v4/view/…
  • Michell Bak
    Michell Bak almost 10 years
    Yes, that bug was created right after I posted this question. See the comments on the original question.
  • Dario
    Dario almost 10 years
    Oh ok, see now. But anyway, maybe this workaround with state change listener might be useful for others also.
  • Joan Casadellà
    Joan Casadellà over 8 years
    What happens if you have always expanded using setIconofiedByDefault(false) ? It dosen't works... :(
  • bpawlowski
    bpawlowski about 8 years
    Setting always value to showAsAction attribute solves the problem. The important thing is that when always value is not present in showAsAction, expanded SearchView presents close button(cross icon) only if query in SearchView is non-null String. The SearchView.onCloseClicked that handles close button events tells that callback to OnCloseListener is called only if query is empty, if it's not - it's cleared first - but then, after clearing query close button disappears and we are unable to deliver onClose callback to OnCloseListener
  • welshk91
    welshk91 about 8 years
    While disappointing that OnCloseListener doesn't work as you'd think, this is actually a nice, clean solution. Kudos!
  • AJW
    AJW about 7 years
    @Joseph Earl: I'm having a similar problem here: stackoverflow.com/questions/43702055/…. Any thoughts or ideas on how to fix?
  • FindOutIslamNow
    FindOutIslamNow over 6 years
    Full answer: if (Build.VERSION.SdkInt > BuildVersionCodes.NMr1) item.SetOnActionExpandListener(this); else MenuItemCompat.SetOnActionExpandListener(item, this);
  • Federico Alvarez
    Federico Alvarez over 6 years
    Just a hint: this method is called when the user closes the search view (quite obvious, but it took me a few times to realize). The fist time the user click on the X it erases text, and I didnt get that update, on the second click on the X it closes the SearchView and the onClose is invoked. Hope it helps!
  • Admin
    Admin over 5 years
    Answers with a blob of code and some cryptic words isn't particularly clear. Just use natural language to describe why you think this solves the problem, and then show the implementation of the solution.
  • Anubhav
    Anubhav almost 3 years
    Just for anyone who wants to understand what setIconifiedByDefault() does, It Sets the default or resting state of the search field. If true, a single search icon is shown by default and expands to show the text field and other buttons when pressed. Also, if the default state is iconified, then it collapses to that state when the close button is pressed.
  • Akito
    Akito over 2 years
    I did not understand this cryptic "explanation" either, but it still led me to the correct solution in my case. My search view wasn't closing and my setOnCloseListener is very simple. I compared mine with the one from this answer and noticed, that I return true. Since I changed it to false it works fine, now. It's easy to miss such little things, so it helps to compare your own code to foreign examples.