我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
在我的案例中,我使用的是操作栏中的SearchView。用户执行搜索后,键盘将再次弹出。
使用InputMethodManager未关闭键盘。我必须清除Focus并将搜索视图的可聚焦设置为false:
mSearchView.clearFocus();
mSearchView.setFocusable(false);
其他回答
如果要使用Java代码隐藏键盘,请使用以下命令:
InputMethodManager imm = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(fEmail.getWindowToken(), 0);
或者,如果您希望始终隐藏键盘,请在AndroidManifest中使用此选项:
<activity
android:name=".activities.MyActivity"
android:configChanges="keyboardHidden" />
调用此方法以隐藏软键盘
public void hideKeyBoard() {
View view1 = this.getCurrentFocus();
if(view!= null){
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view1.getWindowToken(), 0);
}
}
这对我有用:
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
View v = getCurrentFocus();
boolean ret = super.dispatchTouchEvent(event);
if (v instanceof EditText) {
View w = getCurrentFocus();
int scrcoords[] = new int[2];
w.getLocationOnScreen(scrcoords);
float x = event.getRawX() + w.getLeft() - scrcoords[0];
float y = event.getRawY() + w.getTop() - scrcoords[1];
Log.d("Activity",
"Touch event " + event.getRawX() + "," + event.getRawY()
+ " " + x + "," + y + " rect " + w.getLeft() + ","
+ w.getTop() + "," + w.getRight() + ","
+ w.getBottom() + " coords " + scrcoords[0] + ","
+ scrcoords[1]);
if (event.getAction() == MotionEvent.ACTION_UP
&& (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w
.getBottom())) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getCurrentFocus()
.getWindowToken(), 0);
}
}
return ret;
}
在AndroidManifest.xml中的<activity..>set android:windowSoftInputMode=“stateAlwaysHidden”
这种方法总是不惜任何代价。只要在你想隐藏键盘的地方使用它
public static void hideSoftKeyboard(Context mContext,EditText username){
if(((Activity) mContext).getCurrentFocus()!=null && ((Activity) mContext).getCurrentFocus() instanceof EditText){
InputMethodManager imm = (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(username.getWindowToken(), 0);
}
}
这样使用:
无论Android版本是什么。这种方法肯定会奏效的