我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
您可以简单地将此代码添加到要隐藏软键盘的位置“
// Check if no view has focus:
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
其他回答
一些科特林代码:
从“活动”中隐藏键盘:
(currentFocus ?: View(this))
.apply { (getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
.hideSoftInputFromWindow(windowToken, 0) }
//In Activity
View v = this.getCurrentFocus();
if (v != null) {
InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
//In Fragment
View v = getActivity().getCurrentFocus();
if (v != null) {
InputMethodManager im = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
```
如果您的应用程序以API Level 21或更高为目标,则可以使用默认方法:
editTextObj.setShowSoftInputOnFocus(false);
确保在EditText XML标记中设置了以下代码。
<EditText
....
android:enabled="true"
android:focusable="true" />
这是工作。。
只需在函数中传递当前活动实例
public void isKeyBoardShow(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); // hide
} else {
imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); // show
}
}
Kotlin中的Wiki答案:
1-在文件中创建顶级函数(例如,包含所有顶级函数的文件):
fun Activity.hideKeyboard(){
val imm = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
var view = currentFocus
if (view == null) { view = View(this) }
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
2-然后在你需要的任何活动中调用它:
this.hideKeyboard()