我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
我正在使用以下Kotlin Activity扩展:
/**
* Hides soft keyboard if is open.
*/
fun Activity.hideKeyboard() {
currentFocus?.windowToken?.let {
(getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager?)
?.hideSoftInputFromWindow(it, InputMethodManager.HIDE_NOT_ALWAYS)
}
}
/**
* Shows soft keyboard and request focus to given view.
*/
fun Activity.showKeyboard(view: View) {
view.requestFocus()
currentFocus?.windowToken?.let {
(getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager?)
?.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
}
其他回答
更新:我不知道为什么这个解决方案不再有效(我刚刚在Android 23上测试过)。请改用Saurabh Pareek的溶液。这里是:
InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
//Hide:
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
//Show
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
旧答案:
//Show soft-keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//hide keyboard :
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
如果您需要在片段中隐藏键盘,则此方法有效。
public static void hideSoftKeyboard(Context context, View view) {
if (context != null && view != null) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
对于视图,只需传入
getView() method
这对我有用。。
EditText editText=(EditText)findViewById(R.id.edittext1);
放在onClick()中的代码行下面
editText.setFocusable(false);
editText.setFocusableInTouchMode(true);
这里隐藏键盘,当我们单击按钮时,当我们触摸EditText键盘时,将显示。
(OR)
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
用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();
}
有时,您可能有一个活动包含包含editText的行的列表视图,因此您必须在清单SOFT_INPUT_ADJUST_PAN中进行设置,然后出现键盘,这很烦人。
如果您将以下工作错误放置在onCreate的末尾,则它会起作用
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
},100);