[ACCEPTED]-SearchView's OnCloseListener doesn't work-android-actionbar

Accepted answer
Score: 157

I also meet this problem, and I have no 3 choice but give up "oncloselistener". Instead, you 2 can get your menuItem, then setOnActionExpandListener. Then override 1 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;
}
Score: 63

For Android API 14+ (ICS and greater) use 1 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

Score: 31

For this problem I came up with something 1 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);

}
Score: 20

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

Anyway, as a workaround 4 i used state change listener (when SearchView 3 is detached from action bar, it is also 2 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 1 in my case.


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

Score: 12

I ended up using a bit of a hack, that works 5 well for my purpose - not sure it'll work 4 with all purposes. Anyway, I'm doing a check 3 to see if the search query is empty. This 2 is not really related to the SearchView's OnCloseListener though 1 - 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; }
        });
Score: 11

Well, this solved my problem:

Menu item with 1 showAsAction="always"

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

and in activity

searchView.setOnCloseListener(new OnCloseListener() {

        @Override
        public boolean onClose() {

            Log.i("SearchView:", "onClose");
            searchView.onActionViewCollapsed();
            return false;
        }
    });
Score: 4

In order to make the OnCloseListener work, make sure that 1 showAsAction is set to always in the search menu item.

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

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

Create the menu item with the app:showAsAction set to always.

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

When 3 creating the SearchView in the onCreateOptionsMenu method do something 2 similar

inflater.inflate(R.menu.menu_search, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView search = (SearchView) item.getActionView();
search.setQueryHint(getString(R.string.search_brand_item));
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
  @Override
  public boolean onQueryTextSubmit(String query) {
    // add your code
    return false;
  }

  @Override
  public boolean onQueryTextChange(String newText) {
    // add your code 
    return false;
  }
});
search.setOnCloseListener(new SearchView.OnCloseListener() {
  @Override
  public boolean onClose() {
    // add your code here
    return false;
  }
});
search.setIconifiedByDefault(true); // make sure to set this to true

The search.setIconifiedByDefault(true) needs to be set to true to call 1 the onClose() method on the SearchView.OnCloseListener() created above.

Score: 2

I have encountered the same problem with 13 onCloseListener not invoking for the SearchView. Understand 12 from the bug issue raised in 25758, and some 11 postings I have read, to invoke onCloseListener, you 10 need to set:

searchView.setIconifiedByDefault(true);

But for my case I wanted to 9 have the search view opened & not iconified 8 all the time. I manage to resolve this by 7 adding one more line below:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.search_bar, menu);
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    searchView = (SearchView) menu.findItem(R.id.search).getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setOnQueryTextListener(queryTextListener);
    searchView.setIconifiedByDefault(true);
    searchView.setIconified(false);
    return true;
}

The searchView.setIconified(false) will 6 cause the searchView to open up, despite 5 setting the default to iconified to true 4 in the previous line. In this way, I managed 3 to have both a SearchView that opens up 2 all the time & having it invoke the 1 onCloseListener.

Score: 2
    searchView.setOnCloseListener {
        d("click", "close clicked")
        return@setOnCloseListener false
    }

if you click on close searchView ->

D/click: close 1 clicked

Score: 1

For MenuItemCompat problem I added ViewTreeObserver to 2 track the visibility state. You can check 1 my answer here: https://stackoverflow.com/a/28762632/1633609

Score: 1

I used the SearchView close button and set 1 a setOnClickListener on it

searchView.findViewById<ImageView>(R.id.search_close_btn).setOnClickListener {
    searchView.setQuery("", false)
    searchView.clearFocus()
}
Score: 0

The reason the OnCloseListener is not called is because 3 there is a bug in the Android code -- the 2 listener is only called if you also call 1 setIconifiedByDefault(true).

Score: 0

seems an old thread already, but I thought 9 I got the same problem API 18 in the first 8 beginning. After googled around, found 7 this thread, another hour read the javadoc 6 tried and errored for something I don't 5 pretend fully understand in javadoc, the 4 following work for me now:

searchView.setIconifiedByDefault(true);

   // OnQueryTextListener
   @Override
   public boolean onQueryTextSubmit(String query) {
      Log.d(tag, "onQueryTextSubmit: " + query);
      return true;
   }

   @Override
   public boolean onQueryTextChange(String query) {
      Log.d(tag, "onQueryTextChange: " + query);
      return true;
   }

   // OnCloseListener
   @Override
   public boolean onClose() {
      Log.w(tag, "onClose: ");
      return false;
   }

I played with 3 true/false a bit, that somehow makes the 2 difference, and it works for me now. Hopefully, it 1 could save someone time.

Score: 0

It's a workaround but has worked for me

  searchView.setOnQueryTextListener(new android.widget.SearchView.OnQueryTextListener() {

                String lastText;

                @Override
                public boolean onQueryTextChange(final String newText) {
                    if (lastText != null && lastText.length() > 1 && newText.isEmpty()) {
                        // close ctn clicked

                        return true;
                    }
}

0

Score: 0

I encountered this issue while trying to 3 detect the showing/dismissal of the SearchView. I 2 ended up using a different listener and 1 it worked for what I need:

        setOnQueryTextFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                // SearchView is being shown
            } else {
                // SearchView was dismissed
            }
        }
Score: 0
searchView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
  @Override
  public void onViewAttachedToWindow(View v) {
    System.out.println("This is Fired When Search view was Expanded");
  }

  @Override
  public void onViewDetachedFromWindow(View v) {
    System.out.println("This is Fired When Search view was Closed");
  }
});

0

More Related questions