我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
从碎片移动到碎片时
fun hideKeyboard(activity: Activity?): Boolean {
val inputManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
if (inputManager != null) {
val currentFocus = activity?.currentFocus
if (currentFocus != null) {
val windowToken = currentFocus.windowToken
if (windowToken != null) {
return inputManager.hideSoftInputFromWindow(windowToken, 0)
}
}
}
return false
}
fun showKeyboard(editText: EditText) {
val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(editText.windowToken, 0)
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0)
editText.requestFocus()
}
其他回答
现在,将近12年后,我们终于有了一种官方的、向后兼容的方式来实现AndroidX Core 1.5+:
fun View.hideKeyboard() = ViewCompat.getWindowInsetsController(this)
?.hide(WindowInsetsCompat.Type.ime())
或特别针对片段:
fun Fragment.hideKeyboard() = ViewCompat.getWindowInsetsController(requireView())
?.hide(WindowInsetsCompat.Type.ime())
public static void closeInput(final View caller) {
caller.postDelayed(new Runnable() {
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) caller.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(caller.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}, 100);
}
此方法通常有效,但有一个条件:不能设置android:windowSoftInputMode=“any_of_themes”
final RelativeLayout llLogin = (RelativeLayout) findViewById(R.id.rl_main);
llLogin.setOnTouchListener(
new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent ev) {
InputMethodManager imm = (InputMethodManager) this.getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
return false;
}
});
Meier的解决方案也适用于我。在我的例子中,我的应用程序的顶层是一个选项卡宿主,我想在切换选项卡时隐藏关键字-我从选项卡宿主视图获取窗口令牌。
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
public void onTabChanged(String tabId) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(tabHost.getApplicationWindowToken(), 0);
}
}
隐藏软键盘也很有用:
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
);
这可用于抑制软键盘,直到用户实际触摸editText View。