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

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


当前回答

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

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)

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

其他回答

如果有人感兴趣的话,我已经为Kotlin写了一个小扩展,但没有太多测试:

fun Fragment.hideKeyboard(context: Context = App.instance) {
    val windowToken = view?.rootView?.windowToken
    windowToken?.let {
        val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(windowToken, 0)
    }
}

App.instance是存储在Application中的静态“this”Application对象

更新:在某些情况下,windowToken为空。我增加了使用反射来检测键盘是否关闭的额外关闭方式

/**
 * If no window token is found, keyboard is checked using reflection to know if keyboard visibility toggle is needed
 *
 * @param useReflection - whether to use reflection in case of no window token or not
 */
fun Fragment.hideKeyboard(context: Context = MainApp.instance, useReflection: Boolean = true) {
    val windowToken = view?.rootView?.windowToken
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    windowToken?.let {
        imm.hideSoftInputFromWindow(windowToken, 0)
    } ?: run {
        if (useReflection) {
            try {
                if (getKeyboardHeight(imm) > 0) {
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
                }
            } catch (exception: Exception) {
                Timber.e(exception)
            }
        }
    }
}

fun getKeyboardHeight(imm: InputMethodManager): Int = InputMethodManager::class.java.getMethod("getInputMethodWindowVisibleHeight").invoke(imm) as Int

通过创建一个扩展来隐藏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()

简单易用的方法,只需调用hideKeyboardFrom(YourActivity.this);隐藏键盘

/**
 * This method is used to hide keyboard
 * @param activity
 */
public static void hideKeyboardFrom(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}

您可以使用下面的扩展来隐藏和显示软键盘

fun Fragment.showKeyboard(view: View) {
    view.isFocusableInTouchMode = true
    view.requestFocus()
    val imm = view.context?.getSystemService(Context.INPUT_METHOD_SERVICE) 
        as InputMethodManager
    imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT) }

fun Fragment.hideKeyboard(view: View) {
    view.clearFocus()
    val imm = view.context?.getSystemService(Context.INPUT_METHOD_SERVICE) 
       as InputMethodManager
    imm.hideSoftInputFromWindow(view.windowToken, 0) }

要调用扩展,只需按照以下片段进行操作

showKeyboard(Your edittext ID)

hideKeboard(Your edittext ID)

用try-catch包围它,这样键盘就已经关闭,应用程序就不会崩溃:

try{

View view = this.getCurrentFocus();
if (view != null) {  
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}catch (Exception e)
{
  e.printStackTrace();
}