How to dismiss keyboard in Android SearchView?

后端 未结 15 1341
萌比男神i
萌比男神i 2020-12-05 06:27

I have a searchView in the ActionBar. I want to dismiss the keyboard when the user is done with input. I have the following queryTextListener on the searchView



        
相关标签:
15条回答
  • 2020-12-05 06:57

    You can use it.

    if (isKeybordShowing(MainActivity.this, MainActivity.this.getCurrentFocus())) {
        onBackPressed();
    }
    
    public boolean isKeybordShowing(Context context, View view) {
        try {
            InputMethodManager keyboard = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            keyboard.hideSoftInputFromWindow(view.getWindowToken(), 0);
            return keyboard.isActive();
        } catch (Exception ex) {
            Log.e("keyboardHide", "cannot hide keyboard", ex);
            return false;
        }
    }
    
    0 讨论(0)
  • 2020-12-05 06:58
     @Override
        public void onResume() {
            super.onResume();
            searchView.clearFocus();
        }
    

    I tried all the answers above but none worked, clearing focus onResume worked for me

    0 讨论(0)
  • 2020-12-05 07:01

    Why dont you try this? When you touch the X button, you trigger a focus on the searchview no matter what.

    ImageView closeButton = (ImageView)searchView.findViewById(R.id.search_close_btn);
            closeButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EditText et = (EditText) findViewById(R.id.search_src_text);
                    et.setText("");`enter code here`
                    searchView.setQuery("", false);
                    searchView.onActionViewCollapsed();
                    menuSearch.collapseActionView();
                }
            });
    
    0 讨论(0)
提交回复
热议问题