Richard Le Mesurier
Richard Le Mesurier

Reputation: 29714

SearchView listen for IME actions

How can I listen for IME actions on a SearchView? Since it is not a subclass of EditText.

What I want to do is to handle when the user presses the "enter" key on the keyboard and there is no text entered.

The problem with there being no text is that OnQueryTextListener.onQueryTextSubmit() is only triggered if the user has entered text.

Upvotes: 2

Views: 1717

Answers (2)

Täg
Täg

Reputation: 431

With androidx.appcompat.widget.SearchView, you can use:

setOnQueryTextListener(object : SearchView.OnQueryTextListener {
    override fun onQueryTextSubmit(query: String): Boolean {
         return true
    }

    override fun onQueryTextChange(newText: String): Boolean {
         return true
    }
})

Upvotes: 2

Dhinakaran Thennarasu
Dhinakaran Thennarasu

Reputation: 3356

How about getting EditText of the searchview and using OnEditorAction?

final SearchView searchView = (SearchView) findViewById(R.id.searchView);
int searchViewPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
EditText searchPlateEditText = (EditText) searchView.findViewById(searchViewPlateId);
searchPlateEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            if(!TextUtils.isEmpty(v.getText().toString())){
                //Text entered
            }
            else {
                //no string
            }
        }
        return true;
    }

});

Upvotes: 4

Related Questions