Behnam
Behnam

Reputation: 6620

How to prevent SearchView from auto-clearing the searched text

Normal Behavior:

My desired behavior:


I have read official docs for SearchView, and guides from here, and also here, but haven't had any luck.

EDIT: I discovered that this text reset happens whenever I scroll my ViewPager.

Upvotes: 2

Views: 1464

Answers (2)

Simas
Simas

Reputation: 44158

If your search widget calls another activity to handle the query, it gets cleared because the activity is newly created.

Therefore you need to set the query manually from 2 places:

  • onCreateOptionsMenu where you initialize your search widget
  • onNewIntent where you receive your query

Why from 2 places? Because if the search-handling activity is newly created, onNewIntent is called first and the search widget is not yet ready to be used. In that case save the query at onNewIntent and set it at onCreateOptionsMenu. Otherwise it can be directly set at onNewIntent.

Here's an example:

private String mQuery;
private SearchView mSearchView;

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    mQuery = intent.getStringExtra(SearchManager.QUERY);
    if (mSearchView != null) {
        mSearchView.setQuery(mQuery, false);
    }
    // Do something with the new query
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the actionbar items
    getMenuInflater().inflate(R.menu.actionbar_items, menu);

    // Get SearchView and set the searchable configuration
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    mSearchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
    mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

    // Disable collapsing the search widget
    mSearchView.setIconifiedByDefault(false);
    // Set the query
    mSearchView.setQuery(mQuery, false);

    return true;
}

Upvotes: 0

Pedro Oliveira
Pedro Oliveira

Reputation: 20500

Try this:

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

        @Override
        public boolean onQueryTextChange(String newText)
        {
            return false;
        }
    });

Upvotes: 2

Related Questions