I add a search item to ActionBar as follows:

SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.menu_action_search) .getActionView(); if (null != searchView) { searchView.setSearchableInfo(searchManager .getSearchableInfo(getComponentName())); searchView.setIconifiedByDefault(true); } 

I put the handler - everything works fine here (details can be found here ).

But further in the code (in another method), I need to access this input line in order to put my value there ... I can not figure out how to do this?

upd: You can make a field inside the SearchView searchView class and using the field, manage the search text from any searchView.setQuery("", false); method searchView.setQuery("", false); .

But, I would like to find a way to access SearchView without creating a field.

  • make this line a field of class and it will be available in all methods of the class - pavlofff
  • I understand this way. But I don’t want to put it in the field, since this is the Activity class and then I’ll have to think about preserving the value of this field ... I would like to access the text through existing objects - AndreyEKB

1 answer 1

Try this:

 SearchView searchView = (SearchView)findViewById(R.id.action_search); if(searchView!=null){ searchView.setQuery("foo",false); } 

Disadvantages of this method:

  • heavy search in the whole view tree (you can search in the toolbar)
  • it will not be in onCreate activity
  • depending on the showAsAction value, it simply may not be.

Therefore, it is better to cache in onCreateOptionsMenu in the activity property.

  • Thank! I decided to make searchView a class field. - AndreyEKB