how to listen to keyboard search button in searchView

learner picture learner · Oct 10, 2014 · Viewed 22.1k times · Source

I have a SearchView. When the user clicks on the keyboard search button, I need to make a server call. What does the code for the listener look like? I am thinking I have to use OnClickListener. But the internal code for knowing it's the search button, I am not sure how to determine that.

Answer

Qadir Hussain picture Qadir Hussain · Oct 10, 2014

I have done like this

the onQueryTextSubmit is the method you are looking for.

set setOnQueryTextListener on your search view.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);

    MenuItem searchItem = menu.findItem(R.id.search_city);
    searchView = (SearchView) searchItem.getActionView();
    searchView.setQueryHint("Search View Hint");

    searchView.setOnQueryTextListener(new OnQueryTextListener() {

        @Override
        public boolean onQueryTextChange(String newText) {
            //Log.e("onQueryTextChange", "called");
            return false;
        }

        @Override
        public boolean onQueryTextSubmit(String query) {


            // Do your task here

            return false;
        }

    });

    return true;
}

hope this help