我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
在某些情况下,除了所有其他方法外,这种方法都可以工作。这节省了我的一天:)
public static void hideSoftKeyboard(Activity activity) {
if (activity != null) {
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (activity.getCurrentFocus() != null && inputManager != null) {
inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
inputManager.hideSoftInputFromInputMethod(activity.getCurrentFocus().getWindowToken(), 0);
}
}
}
public static void hideSoftKeyboard(View view) {
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputManager != null) {
inputManager.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();
快乐编码。。。
现在,将近12年后,我们终于有了一种官方的、向后兼容的方式来实现AndroidX Core 1.5+:
fun View.hideKeyboard() = ViewCompat.getWindowInsetsController(this)
?.hide(WindowInsetsCompat.Type.ime())
或特别针对片段:
fun Fragment.hideKeyboard() = ViewCompat.getWindowInsetsController(requireView())
?.hide(WindowInsetsCompat.Type.ime())
//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);
}
```
这个对我有用,你只需要传递里面的元素。
InputMethodManager imm=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(AutocompleteviewDoctorState.getWindowToken(), 0);
如果您的应用程序以API Level 21或更高为目标,则可以使用默认方法:
editTextObj.setShowSoftInputOnFocus(false);
确保在EditText XML标记中设置了以下代码。
<EditText
....
android:enabled="true"
android:focusable="true" />