我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
通过创建一个扩展来隐藏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()
其他回答
对于kotlin用户,这里有一个kotlin扩展方法,它适用于我的用例:
fun View.hideKeyboard() {
val imm = this.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
将其放在名为ViewExtensions的文件中(或其他文件),并像普通方法一样在视图中调用它。
您可以使用InputMethodManager强制Android隐藏虚拟键盘,调用hideSoftInputFromWindow,传入包含焦点视图的窗口的标记。
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
这将在所有情况下强制隐藏键盘。在某些情况下,您需要将InputMethodManager.HIDE_IMPLICIT_ONLY作为第二个参数传递,以确保仅在用户未显式强制显示键盘时(通过按住菜单)隐藏键盘。
注意:如果您想在Kotlin中执行此操作,请使用:上下文getSystemService(Context.INPUT_METHOD_SERVICE)作为InputMethodManager
Kotlin语法
// Only runs if there is a view that is currently focused
this.currentFocus?.let { view ->
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.hideSoftInputFromWindow(view.windowToken, 0)
}
Kotlin版本
val imm: InputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
//Hide:
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
//Show
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
我已经尝试了所有的解决方案,但没有一个解决方案适合我,所以我找到了我的解决方案:您应该有如下布尔变量:
public static isKeyboardShowing = false;
InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
在触摸屏事件中,您可以拨打:
@Override
public boolean onTouchEvent(MotionEvent event) {
if(keyboardShowing==true){
inputMethodManager.toggleSoftInput(InputMethodManager.RESULT_UNCHANGED_HIDDEN, 0);
keyboardShowing = false;
}
return super.onTouchEvent(event);
}
在EditText中的任何位置:
yourEditText.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
yourClass.keyboardShowing = true;
}
});
请在onCreate()中尝试以下代码
EditText edtView = (EditText) findViewById(R.id.editTextConvertValue);
edtView.setInputType(InputType.TYPE_NULL);