我的布局中有一个EditText和一个Button。

在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?


当前回答

在某些情况下,除了所有其他方法外,这种方法都可以工作。这节省了我的一天:)

public static void hideSoftKeyboard(Activity activity) {
    if (activity != null) {
        InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (activity.getCurrentFocus() != null && inputManager != null) {
            inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
            inputManager.hideSoftInputFromInputMethod(activity.getCurrentFocus().getWindowToken(), 0);
        }
    }
}

public static void hideSoftKeyboard(View view) {
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputManager != null) {
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}

其他回答

在Kotlin中,只需使用这两种方法来显示和隐藏键盘。

fun showKeyboard() =
    (context.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as? InputMethodManager)!!
        .toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)

fun hideKeyboard(view: View) =
    (context.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as? InputMethodManager)!!
        .hideSoftInputFromWindow(view.windowToken, 0)

这里的视图是您当前的视图,

通过创建一个扩展来隐藏Kotlin中的软键盘,您可以全局使用该扩展。为此,需要创建一个Singleton类。

object Extensions {
    
      fun View.hideKeyboard() {
            val inputMethodManager =                                                 
            context.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE)           
            as InputMethodManager
            inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
        }
    }

在需要隐藏键盘的片段类的活动中,可以使用mainlayout id调用此函数,如下所示

//constraintEditLayout is my main view layout, if you are using other layout like relative or linear layouts you can call with that layout id
constraintEditLayout.hideKeyboard()

Kotlin版本:

fun showKeyboard(mEtSearch: EditText, context: Context) {
        mEtSearch.requestFocus()
        val imm: InputMethodManager =
            context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(mEtSearch, 0)
}

请在onCreate()中尝试以下代码

EditText edtView = (EditText) findViewById(R.id.editTextConvertValue);
edtView.setInputType(InputType.TYPE_NULL);

作为这一全面解决方案的替代方案,如果您想从任何地方关闭软键盘,而没有对用于打开键盘的(EditText)字段的引用,但仍然希望在该字段被聚焦时进行此操作,则可以使用(从“活动”):

if (getCurrentFocus() != null) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}