我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
在Android中,要通过InputMethodManage隐藏Vkeyboard,您可以通过传递包含焦点视图的窗口的标记来隐藏SoftInputFromWindow。
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager im =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
通过调用editText.clearFocus(),然后调用InputMethodManager.HIDE_IMPLICIT_ONLY甚至可以工作
其他回答
在我的案例中,我使用的是操作栏中的SearchView。用户执行搜索后,键盘将再次弹出。
使用InputMethodManager未关闭键盘。我必须清除Focus并将搜索视图的可聚焦设置为false:
mSearchView.clearFocus();
mSearchView.setFocusable(false);
用try-catch包围它,这样键盘就已经关闭,应用程序就不会崩溃:
try{
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}catch (Exception e)
{
e.printStackTrace();
}
对于Xamarin.Android:
public void HideKeyboard()
{
var imm = activity.GetSystemService(Context.InputMethodService).JavaCast<InputMethodManager>();
var view = activity.CurrentFocus ?? new View(activity);
imm.HideSoftInputFromWindow(view.WindowToken, HideSoftInputFlags.None);
}
这对我有用。
public static void hideKeyboard(Activity act, EditText et){
Context c = act.getBaseContext();
View v = et.findFocus();
if(v == null)
return;
InputMethodManager inputManager = (InputMethodManager) c.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
在AndroidManifest.xml中的<activity..>set android:windowSoftInputMode=“stateAlwaysHidden”