我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
在Kotlin
fun hideKeyboard(activity: BaseActivity) {
val view = activity.currentFocus?: View(activity)
val imm = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
其他回答
在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甚至可以工作
您也可以使用此代码段在Kotlin中隐藏键盘。
fun hideKeyboard(activity: Activity?) {
val inputManager: InputMethodManager? =
activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as?
InputMethodManager
// check if no view has focus:
val v = activity?.currentFocus ?: return
inputManager?.hideSoftInputFromWindow(v.windowToken, 0)
}
如果您想在单元或功能测试期间关闭软键盘,可以通过单击测试中的“后退按钮”来完成:
// Close the soft keyboard from a Test
getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
我将“后退按钮”放在引号中,因为上面的内容不会触发所讨论的活动的onBackPressed()。它只是关闭键盘。
在继续之前,请确保暂停一段时间,因为关闭后退按钮需要一段时间。因此,在短暂暂停后(1秒足够长),才能注册随后的视图等单击。
这对我有用。
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);
}
对于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);
}