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

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


当前回答

在AndroidManifest.xml中的<activity..>set android:windowSoftInputMode=“stateAlwaysHidden”

其他回答

如果您的应用程序以API Level 21或更高为目标,则可以使用默认方法:

editTextObj.setShowSoftInputOnFocus(false);

确保在EditText XML标记中设置了以下代码。

<EditText  
    ....
    android:enabled="true"
    android:focusable="true" />

•通过扩展功能的Kotlin版本

使用kotlin扩展功能,显示和隐藏软键盘非常简单。

扩展功能.kt

import android.app.Activity
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.fragment.app.Fragment

fun Activity.hideKeyboard(): Boolean {
    return (getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
        .hideSoftInputFromWindow((currentFocus ?: View(this)).windowToken, 0)
}

fun Fragment.hideKeyboard(): Boolean {
    return (context?.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
        .hideSoftInputFromWindow((activity?.currentFocus ?: View(context)).windowToken, 0)
}

fun EditText.hideKeyboard(): Boolean {
    return (context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
        .hideSoftInputFromWindow(windowToken, 0)
}

fun EditText.showKeyboard(): Boolean {
    return (context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
        .showSoftInput(this, 0)
}

•使用

现在,在您的Activity或Fragment中,hideKeyboard()可以清晰地访问,也可以从EditText的实例调用它,例如:

editText.hideKeyboard()

只需在EditTect视图中添加此属性即可隐藏键盘。

android:focusable="false"

在绝望中尝试了所有的方法,结合了所有方法,当然,在Android 4.0.3中键盘不会关闭(它在Honeicomb AFAIR中确实有效)。

然后我突然发现了一个明显获胜的组合:

textField.setRawInputType(InputType.TYPE_CLASS_TEXT |InputType.TYPE_TEXT_VARIATION_NORMAL);

结合你平时的食谱

blahblaj.hideSoftInputFromWindow ...

希望这能阻止某人自杀。。我很接近它。当然,我不知道为什么它会起作用。

您可以使用InputMethodManager强制Android隐藏虚拟键盘,调用hideSoftInputFromWindow,传入包含焦点视图的窗口的标记。

// 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);
}

这将在所有情况下强制隐藏键盘。在某些情况下,您需要将InputMethodManager.HIDE_IMPLICIT_ONLY作为第二个参数传递,以确保仅在用户未显式强制显示键盘时(通过按住菜单)隐藏键盘。

注意:如果您想在Kotlin中执行此操作,请使用:上下文getSystemService(Context.INPUT_METHOD_SERVICE)作为InputMethodManager

Kotlin语法

// Only runs if there is a view that is currently focused
this.currentFocus?.let { view ->
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
    imm?.hideSoftInputFromWindow(view.windowToken, 0)
}