我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
作为这一全面解决方案的替代方案,如果您想从任何地方关闭软键盘,而没有对用于打开键盘的(EditText)字段的引用,但仍然希望在该字段被聚焦时进行此操作,则可以使用(从“活动”):
if (getCurrentFocus() != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
其他回答
非常简单的方法
我在所有的项目中都这样做,并且像做梦一样工作。在声明layout.xml中,只需添加以下一行:
android:focusableInTouchMode="true"
完整代码示例:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="true">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</android.support.constraint.ConstraintLayout>
如果您的应用程序以API Level 21或更高为目标,则可以使用默认方法:
editTextObj.setShowSoftInputOnFocus(false);
确保在EditText XML标记中设置了以下代码。
<EditText
....
android:enabled="true"
android:focusable="true" />
/**
*
* Hide I Said!!!
*
*/
public static boolean hideSoftKeyboard(@NonNull Activity activity) {
View currentFocus = activity.getCurrentFocus();
if (currentFocus == null) {
currentFocus = activity.getWindow().getDecorView();
if (currentFocus != null) {
return getSoftInput(activity).hideSoftInputFromWindow(currentFocus.getWindowToken(), 0, null);
}
}
return false;
}
public static boolean hideSoftKeyboard(@NonNull Context context) {
if(Activity.class.isAssignableFrom(context.getClass())){
return hideSoftKeyboard((Activity)context);
}
return false;
}
public static InputMethodManager getSoftInput(@NonNull Context context) {
return (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
}
//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);
}
```
记下所有这些答案,简单地说,我写了一个常用的方法:
/**
* hide soft keyboard in a activity
* @param activity
*/
public static void hideKeyboard (Activity activity){
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
if (activity.getCurrentFocus() != null) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
}