How to close a SearchView programmatically on back pressed?

后端 未结 8 1936
余生分开走
余生分开走 2021-01-07 07:39

I have the same question which I found here which I will re-iterate because the solution is not 100% exactly what I need:

I currently have a SearchVie

8条回答
  •  终归单人心
    2021-01-07 08:24

    Based on @Archana answer, the onBackPressed() should be like :

    @Override
    public void onBackPressed() {    
        hideSoftKeyboard();
        if (!searchView.isIconified()) {
            searchView.setIconified(true);
        } else {
            super.onBackPressed();
        }
    }
    
    private void hideSoftKeyboard(){
        View view = activity.getCurrentFocus ();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService (Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow (view.getWindowToken (), 0);
        }
    }
    

    or you can also override the onKeyDown()

    @Override
    public boolean onKeyDown (int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            hideSoftKeyboard ();
            if (! searchView.isIconified ()) {
                searchView.setIconified (true);
            } 
            return true;
        }
        return super.onKeyDown (keyCode, event);
    }
    
    private void hideSoftKeyboard() {
        View view = activity.getCurrentFocus ();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService (Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow (view.getWindowToken (), 0);
        }
    }
    

提交回复
热议问题