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

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


当前回答

public void setKeyboardVisibility(boolean show) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if(show){
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    }else{
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0);
    }
}

其他回答

我使用Kotlin扩展来显示和隐藏键盘。

fun View.showKeyboard() {
  this.requestFocus()
  val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
  inputMethodManager.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

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

我的解决方案:

用活动构造它(视图是可选的),使用处理程序发布它(有一些延迟,例如100ms更好)。直接调用输入管理器有时不起作用。只有在工作时才能获得“活动”。我认为这很正常。

如果您可以在通话时获取根视图组或编辑视图,只需发送它即可获得更好的结果。

public class CloseSoftKeyboardRunnable implements Runnable
{
    Activity activity;
    View view;  // for dialog will occur context getcurrentfocus == null. send a rootview to find currentfocus.

    public CloseSoftKeyboardRunnable(Activity activity, View view)
    {
        this.activity = activity;
        this.view = view;
    }

    public CloseSoftKeyboardRunnable(Activity activity)
    {
        this.activity = activity;
    }
    @Override
    public void run() {
        if (!activity.isFinishing())
        {
            InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);

            if (view == null) {
                view = activity.getCurrentFocus();
            }
            else
            {
                try {
                    view = ((ViewGroup)view).getFocusedChild();
                }
                catch ( Exception e) {}
            }

            Window window =  activity.getWindow();
            
            if (window != null)
            {
                if (view == null) {
                    try {
                        view = window.getDecorView();
                        view = ((ViewGroup)view).getFocusedChild();
                    }
                    catch ( Exception e) {}
                }

                if (view == null) {
                    view = window.getDecorView();
                }

                if (view != null) {
                    if (view instanceof EditText)
                    {
                        EditText edittext = ((EditText) view);
                        edittext.setText(edittext.getText().toString()); // reset edit text bug on some keyboards bug
                        edittext.clearFocus();
                    }

                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
                window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            }
        }
    }
}

下面的代码将帮助您创建可以从任何地方调用的通用函数。

import android.app.Activity
import android.content.Context
import android.support.design.widget.Snackbar
import android.view.View
import android.view.inputmethod.InputMethodManager

public class KeyboardHider {
    companion object {

        fun hideKeyboard(view: View, context: Context) {
            val inputMethodManager = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
            inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
        }

    }

}

使用一行代码从任何地方调用Above方法。

CustomSnackbar.hideKeyboard(view, this@ActivityName)

视图可以是任何内容,例如活动的根布局。

只需调用下面的方法,如果键盘显示,它将隐藏键盘。

public void hideKeyboard() {
    try {
        InputMethodManager inputmanager = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputmanager != null) {
            inputmanager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
    } catch (Exception var2) {
    }

}

感谢上帝,它在11年后得到了官方支持

首先将依赖实现“androidx.core:core-ktx:1.7.0”添加到appgradle

然后从ViewCompat或WindowCompat类获取InsetsController。

最后使用InsetsController的hide()和show()函数

已编辑添加对Dialog的支持。在BottomSheetDialog中提供@隆德夫。使用更安全的方式获取活动,而不是直接从上下文中强制转换。

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.ContextWrapper
import android.view.View
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment

fun View.showKeyboard() = ViewCompat.getWindowInsetsController(this)?.show(WindowInsetsCompat.Type.ime())
fun View.hideKeyboard() = ViewCompat.getWindowInsetsController(this)?.hide(WindowInsetsCompat.Type.ime())

fun Dialog.showKeyboard() = window?.decorView?.showKeyboard()
fun Dialog.hideKeyboard() = window?.decorView?.hideKeyboard()

fun Context.showKeyboard() = getActivity()?.showKeyboard()
fun Context.hideKeyboard() = getActivity()?.hideKeyboard()

fun Fragment.showKeyboard() = activity?.showKeyboard()
fun Fragment.hideKeyboard() = activity?.hideKeyboard()

fun Activity.showKeyboard() = WindowCompat.getInsetsController(window, window.decorView)?.show(WindowInsetsCompat.Type.ime())
fun Activity.hideKeyboard() = WindowCompat.getInsetsController(window, window.decorView)?.hide(WindowInsetsCompat.Type.ime())

fun Context.getActivity(): Activity? {
    return when (this) {
        is Activity -> this
        is ContextWrapper -> this.baseContext.getActivity()
        else -> null
    }
}

下面是旧的anwser

下面是github上的简单项目

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.ContextWrapper
import android.view.View
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment

fun View.showKeyboard() = ViewCompat.getWindowInsetsController(this)?.show(WindowInsetsCompat.Type.ime())
fun View.hideKeyboard() = ViewCompat.getWindowInsetsController(this)?.hide(WindowInsetsCompat.Type.ime())

fun Dialog.showKeyboard() = window?.decorView?.showKeyboard()
fun Dialog.hideKeyboard() = window?.decorView?.hideKeyboard()

fun Context.showKeyboard() = getActivity()?.showKeyboard()
fun Context.hideKeyboard() = getActivity()?.hideKeyboard()

fun Fragment.showKeyboard() = activity?.showKeyboard()
fun Fragment.hideKeyboard() = activity?.hideKeyboard()

fun Activity.showKeyboard() = WindowCompat.getInsetsController(window, window.decorView)?.show(WindowInsetsCompat.Type.ime())
fun Activity.hideKeyboard() = WindowCompat.getInsetsController(window, window.decorView)?.hide(WindowInsetsCompat.Type.ime())

fun Context.getActivity(): Activity? {
    return when (this) {
        is Activity -> this
        is ContextWrapper -> this.baseContext.getActivity()
        else -> null
    }
}