跳至主要内容

How to close SearchView in android with ActionbarSherlock or android ActionBar


How to close SearchView in android with ActionbarSherlock or android ActionBar

When I use a search view for search something in android action bar;
u must have create a menu for actionview( SearchView)
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.news_post_list, menu);
    mSearchView = (SearchView) menu.findItem(R.id.item_search).getActionView();
    mSearchView.setQueryHint(getString(R.string.search_hint_news));
    mSearchView.setOnQueryTextListener(this);
    super.onCreateOptionsMenu(menu, inflater);
}
and menu xml is :


<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item 
    android:id="@+id/item_search"
    android:icon="@drawable/ic_action_search"
    android:title="@string/search_hint"
    android:showAsAction="ifRoom"
    android:actionViewClass="com.actionbarsherlock.widget.SearchView"/>
<item
    android:id="@+id/item_tweet_add"
    android:icon="@drawable/contribute"
    android:showAsAction="always"
    android:title="@string/tweet_new"
    android:titleCondensed="@string/tweet_new"/>
</menu>



I input my keywords for search if click search then activity go search like exm:
@Override
public boolean onQueryTextSubmit(String query) {
    Intent intent = new Intent(mContext, NewsSearchActivity.class);
    intent.putExtra("query", query);
    startActivity(intent);
    return true;
}
A new activity start for show you search result. Now I finish this activity or fragment. The search view is open and wait me input (I want it's close).
so you can do like this :
mSearchView.onActionViewCollapsed();
mSearchView.setQuery("", false);
mSearchView.clearFocus();

评论

  1. Hi Jerry, I'm currently working on SherlockListFragment, which has a searchview widget located at the actionbar. However, my searchview is not able to filter anything from my custom ArrayAdapter. Here is the link: http://stackoverflow.com/questions/18002042/searchview-in-sherlocklistfragment

    Do you have any idea about this problem?

    Thank you

    回复删除
    回复
    1. // this is my code in my project. and it's run well. you can do like this.

      private void initSearchView() {
      mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
      @Override
      public boolean onQueryTextSubmit(String query) {
      return false;
      }

      @Override
      public boolean onQueryTextChange(String newText) {
      if (TextUtils.isEmpty(newText) && TextUtils.isEmpty(newText.trim())) {
      searching = false;
      mListView.setAdapter(mClientListAdapter);
      return false;
      } else {
      searching = true;
      searchClients(newText);
      return true;
      }
      }
      });
      }

      删除
  2. Hi Jerry, thanks a lot..this one solved my problem, really appreciate the code.

    回复删除

发表评论