我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
试试这个
简单,您可以在活动中调用
public static void hideKeyboardwithoutPopulate(Activity activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(
Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus().getWindowToken(), 0);
}
在您的主活动中调用
hideKeyboardwithoutPopulate(MainActivity.this);
其他回答
对于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);
}
以上答案适用于不同的场景,但如果您想将键盘隐藏在视图中,并努力获得正确的上下文,请尝试以下操作:
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
hideSoftKeyBoardOnTabClicked(v);
}
}
private void hideSoftKeyBoardOnTabClicked(View v) {
if (v != null && context != null) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
并从构造函数获取上下文:)
public View/RelativeLayout/so and so (Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
init();
}
每次都像魔术般
private void closeKeyboard() {
InputMethodManager inputManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
private void openKeyboard() {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
}
}
如果您想在单元或功能测试期间关闭软键盘,可以通过单击测试中的“后退按钮”来完成:
// Close the soft keyboard from a Test
getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
我将“后退按钮”放在引号中,因为上面的内容不会触发所讨论的活动的onBackPressed()。它只是关闭键盘。
在继续之前,请确保暂停一段时间,因为关闭后退按钮需要一段时间。因此,在短暂暂停后(1秒足够长),才能注册随后的视图等单击。
简单的方法家伙:试试这个。。。
private void closeKeyboard(boolean b) {
View view = this.getCurrentFocus();
if(b) {
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
else {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view, 0);
}
}