Question Detail

How to use keyboard Search button and handle its click in android?

6 years ago Views 9158 Visit Post Reply

I have an EditText which is for Seachbar in Android App, Now I want to search or trigger the function on press Search button from Keyboard, I have use below mentioned code to perform this task

android:imeOptions="actionSearch"

for show Search button. Now I am stuck on How can I handle its Click Event from Keyboard?
Please Help
Image result for keyboard search Button android


Thread Reply

Anonymous

- 6 years ago

I have use this

the onQueryTextSubmit is the method you are looking for.

set setOnQueryTextListener on your search view.

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

    MenuItem searchItem = m.findItem(R.id.search_name);
    searchView = (SearchView) searchItem.getActionView();
    searchView.setQueryHint("Search by Name");

    searchView.setOnQueryTextListener(new OnQueryTextListener() {

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

        @Override
        public boolean onQueryTextSubmit(String query) {


            // Do your task here

            return false;
        }

    });

    return true;
}

Hemant Sharma

- 6 years ago

In the layout set your input method options to search.

<EditText
    android:imeOptions="actionSearch" 
    android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
 />

In the java add the editor action listener.

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            performSearch();
            return true;
        }
        return false;
    }
});