SearchView.OnCloseListener does not get invoked

后端 未结 9 617
慢半拍i
慢半拍i 2020-12-03 22:23

Im using an action bar and adding a searchView to it. I have implemented the searchView.onCLoseListener but this does not seem to be getting invoked. Any suggestions ?

相关标签:
9条回答
  • 2020-12-03 23:04

    In order call onClose() method from SearchView.OnCloseListener. I made it working in the following way. Add this to your searchview

    searchView.setIconifiedByDefault(true);
    searchView.setOnCloseListener(this);
    

    Now implement this onclick listener

      searchView.findViewById(R.id.search_close_btn)
                    .setOnClickListener(new View.OnClickListener() {
                        @Override
                    public void onClick(View v) {
                        Log.d("called","this is called.");
                        searchView.setQuery("",false);
                        searchView.setIconified(true);
    
                    }
                });
    

    This worked for me. Sharing so that it can help somebody else also. Thanks

    0 讨论(0)
  • 2020-12-03 23:04

    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 creating the SearchView in the onCreateOptionsMenu method do something like this

    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 the onClose() method on the SearchView.OnCloseListener() created above.

    0 讨论(0)
  • 2020-12-03 23:05

    To get notified when the 'x' icon is clicked, I added an on click listener to the SearchView 'x' button.

    Find the SearchView 'x' button by id and attach the OnClickListener:

    mSearchView.findViewById(R.id.search_close_btn)
        .setOnClickListener(this);
    

    The view search_close_btn is present in the SearchView layout provided by the Android framework.

    0 讨论(0)
提交回复
热议问题