Search code examples
androidsearchview

Start Activity with SearchView open


how can I start an activity with a SearchView with the text field open. In this way I could search without having to click on the spyglass. I am using Sherlock Action Bar.

Here is my code:

   @Override
    public boolean onCreateOptionsMenu(Menu menu) {

     final SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
        searchView.setQueryHint("Cerca domande");

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
                if (query.length() != 0) {

                    // handle search here
                    return true;
                }
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

                 if (newText.length()>=3) {
                     new PostTask().execute(newText);   

                     Util.setSharedPreferences(SearchActivity.this, "lastsearch", newText);
                 }
                return false;
            }
        });

        menu.add("Search")
            .setIcon(ic_search_inverse)
            .setActionView(searchView)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);


        listsearch.setOnItemClickListener(this);

     return true;
    }

Thanks.


Solution

  • Tried this?

    searchMenu.expandActionView();
    

    in OnCreateOptionsMenu()

    menu.add("Search")
                .setIcon(ic_search_inverse)
                .setActionView(searchView)
                .expandActionView();
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
    

    you can add focus, open soft-keyboard. So, that everything is ready for user to type in and search.

    But this isn't the standard behavior.