【问题标题】:How to handle a button click that hides the soft keyboard in Android? [duplicate]如何处理在 Android 中隐藏软键盘的按钮单击? [复制]
【发布时间】:2017-10-15 21:27:11
【问题描述】:

Android Studio 2.3、Android 4.3、Galaxy Nexus。

截图:

我希望所选按钮(单击时)隐藏软键盘。

问题:

  1. 此按钮的名称是什么?
  2. 如何处理在片段中单击此按钮?

【问题讨论】:

    标签: android


    【解决方案1】:

    您可以使用以下方法处理按下的后退按钮:

    // When not using fragments
    @Override
    public void onBackPressed() {
        // Check if no view has focus:
        View view = this.getCurrentFocus();
        if (view != null) {  
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
    

    onBackPressed 方法内部的代码在这里找到; Close/hide the Android Soft Keyboard

    // When using a fragment
    fragment.getView().setFocusableInTouchMode(true);
    fragment.getView().requestFocus();
    fragment.getView().setOnKeyListener( new OnKeyListener()
    {
        @Override
        public boolean onKey( View v, int keyCode, KeyEvent event )
        {
            if( keyCode == KeyEvent.KEYCODE_BACK )
            {
                // Check if no view has focus:
                View view = this.getCurrentFocus();
                if (view != null) {  
                    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
            }
            return false;
        }
    } );
    

    【讨论】:

    • 我需要处理 Fragment 中的后退按钮。片段没有方法“onBackPressed”
    • 好的,我会研究解决方案。同时接受我的编辑,以便其他用户可以看到正在使用的片段
    • 当显示键盘并单击返回按钮时,方法“onKey(...)”不会调用。
    【解决方案2】:

    您可以使用onKeyPreIme 方法来处理按钮的点击。

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) { 
        return true;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-15
      • 1970-01-01
      • 2011-12-22
      • 2010-12-27
      • 2011-12-24
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      相关资源
      最近更新 更多