我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
请在onCreate()中尝试以下代码
EditText edtView = (EditText) findViewById(R.id.editTextConvertValue);
edtView.setInputType(InputType.TYPE_NULL);
其他回答
private void hideSoftKeyboard() {
View view = getView();
if (view != null) {
InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
可以为任何视图创建Extension函数
fun View.hideKeyboard() = this.let {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
与活动一起使用的示例
window.decorView.hideKeyboard();
与视图一起使用的示例
etUsername.hideKeyboard();
快乐编码。。。
只需在活动中使用此优化代码:
if (this.getCurrentFocus() != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
对于科特林爱好者。我创建了两个扩展函数。为了隐藏键盘的乐趣,您可以将edittext的实例作为视图传递。
fun Context.hideKeyboard(view: View) {
(getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.apply {
hideSoftInputFromWindow(view.windowToken, 0)
}
}
fun Context.showKeyboard() {
(getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.apply {
toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
}
}
如果您的应用程序以API Level 21或更高为目标,则可以使用默认方法:
editTextObj.setShowSoftInputOnFocus(false);
确保在EditText XML标记中设置了以下代码。
<EditText
....
android:enabled="true"
android:focusable="true" />