手动显示和隐藏软键盘 android

一:在某一个activity中点击任意位置均可以隐藏键盘

val keyboard =getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
//this.currentFocus?.windowToken 是获取当前activity的windowToken
keyboard.hideSoftInputFromWindow(this.currentFocus?.windowToken,0)

二:若输入法已经打开则隐藏,反之则显示
val keyboard = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
keyboard.toggleSoftInput(0,InputMethodManager.HIDE_NOT_ALWAYS)

三:需要接收输入的视图对键盘进行强制打开或隐

val keyboard = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
//keyboard.isActive是键盘的状态,若是打开的则返回true否则返回false
if (keyboard.isActive){
//强制关闭
keyboard.hideSoftInputFromWindow(v.windowToken,0)
}else{
//打开
keyboard.showSoftInput(v,InputMethodManager.SHOW_FORCED)

}

遇到的问题:keyboard.isActive一直返回的都是True,一直没找出是什么原因,本人的解决方法自己定义一个状态值记录
键盘的状态

private var isopen = false

val keyboard = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
//keyboard.isActive是键盘的状态,若是打开的则返回true否则返回false
//
if (isopen){
Log.v("lfl","关闭键盘")
//强制关闭
keyboard.hideSoftInputFromWindow(v.windowToken,0)
isopen = !isopen
}else{
Log.v("lfl","打开键盘")
//打开
keyboard.showSoftInput(v,InputMethodManager.SHOW_FORCED)
isopen = !isopen
}
posted @ 2021-05-08 21:26  哎睡的懒洋洋  阅读(527)  评论(0编辑  收藏  举报