Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android how to focus ActionBar searchView

Hello i need to put some text inside the searchView and focus/expand the searchView widget.

this is what i tried but it doesn't work

@Override
public boolean onCreateOptionsMenu(final Menu menu) {
...
    SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
    searchView.setQuery(this.filtro, false);
    searchView.setFocusable(true);
    searchView.requestFocus();
    searchView.requestFocusFromTouch();
like image 293
max4ever Avatar asked Sep 29 '22 20:09

max4ever


2 Answers

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();
}
like image 123
farmer.chs Avatar answered Oct 24 '22 09:10

farmer.chs


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;
}
like image 4
Owen Zhao Avatar answered Oct 24 '22 07:10

Owen Zhao