我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
我使用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)
}
其他回答
如果这里的所有其他答案都不适合您,那么还有另一种手动控制键盘的方法。
创建一个用于管理EditText的某些财产的函数:
public void setEditTextFocus(boolean isFocused) {
searchEditText.setCursorVisible(isFocused);
searchEditText.setFocusable(isFocused);
searchEditText.setFocusableInTouchMode(isFocused);
if (isFocused) {
searchEditText.requestFocus();
}
}
然后,确保在EditText的焦点上打开/关闭键盘:
searchEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (v == searchEditText) {
if (hasFocus) {
// Open keyboard
((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(searchEditText, InputMethodManager.SHOW_FORCED);
} else {
// Close keyboard
((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(searchEditText.getWindowToken(), 0);
}
}
}
});
现在,每当您想要打开键盘时,请手动调用:
setEditTextFocus(true);
对于结束通话:
setEditTextFocus(false);
如果您想在单元或功能测试期间关闭软键盘,可以通过单击测试中的“后退按钮”来完成:
// Close the soft keyboard from a Test
getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
我将“后退按钮”放在引号中,因为上面的内容不会触发所讨论的活动的onBackPressed()。它只是关闭键盘。
在继续之前,请确保暂停一段时间,因为关闭后退按钮需要一段时间。因此,在短暂暂停后(1秒足够长),才能注册随后的视图等单击。
以下是使用Kotlin隐藏软键盘的最简单方法:
//hides soft keyboard anything else is tapped( screen, menu bar, buttons, etc. )
override fun dispatchTouchEvent( ev: MotionEvent? ): Boolean {
if ( currentFocus != null ) {
val imm = getSystemService( Context.INPUT_METHOD_SERVICE ) as InputMethodManager
imm.hideSoftInputFromWindow( currentFocus!!.windowToken, 0 )
}
return super.dispatchTouchEvent( ev )
}
fun hideKeyboard(appCompatActivity: AppCompatActivity) {
val view = appCompatActivity.currentFocus
val imm = appCompatActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
更新:我不知道为什么这个解决方案不再有效(我刚刚在Android 23上测试过)。请改用Saurabh Pareek的溶液。这里是:
InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
//Hide:
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
//Show
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
旧答案:
//Show soft-keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//hide keyboard :
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);