Android how to focus ActionBar searchView
Try using searchView.setIconified(false)
. This worked for me:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ActionBar actionBar = getActionBar();
SearchView searchView = new SearchView(this);
actionBar.setCustomView(searchView);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
searchView.setQuery("test",true);
searchView.setFocusable(true);
searchView.setIconified(false);
searchView.requestFocusFromTouch();
}
Here is another solution.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
MenuItem menu_search = menu.findItem(R.id.menu_search);
menu_search.setOnActionExpandListener(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) {
//get focus
item.getActionView().requestFocus();
//get input method
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
return true; // Return true to expand action view
}
});
return true;
}
This works for me:
@Override
public boolean onMenuItemActionExpand(MenuItem item)
{
if (sm.isMenuShowing()) {
sm.toggle();
}
searchView.setIconified(true);
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, 32);
searchView.onKeyDown(32, event);
return true;
}
For me the following works:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
...
MenuItem miSearch = menu.findItem(R.id.menu_search);
SearchView mSearchView = (SearchView) miSearch.getActionView();
mSearchView.setOnSearchClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mSearchView.setFocusable(true);
mSearchView.requestFocusFromTouch();
}
});
I use android.support.v7.widget.SearchView. When tried to set mSearchView.setIconified(false);
it entered into an infinite loop.