Search code examples
androidandroid-layoutandroid-searchmanager

When I press the hardware search button, the search bar and keyboard appears. How to 'press the search button' from code?


I've created a searchable activity as described here: http://developer.android.com/guide/topics/search/search-dialog.html. When the user presses the hardware search button, it shows a search bar in the top and keyboard in the bottom.

How can I get the search bar and keyboard to appear when the activity is launched, as if I'd pressed the hardware button?

The reason I don't just create a layout with an EditText and a Button is that I want a consistent experience for the user, so the search bar should look the same whether invoked from the hardware button or from code.

Let me know if you need clarification.


Solution

  • You can start a search from an Activity with onSearchRequested():

        /**
         * onCreate is called when Android starts this Activity from scratch.
         */
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            onSearchRequested();
        }