我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
对于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);
}
其他回答
Kotlin中的Wiki答案:
1-在文件中创建顶级函数(例如,包含所有顶级函数的文件):
fun Activity.hideKeyboard(){
val imm = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
var view = currentFocus
if (view == null) { view = View(this) }
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
2-然后在你需要的任何活动中调用它:
this.hideKeyboard()
fun hideKeyboard(appCompatActivity: AppCompatActivity) {
val view = appCompatActivity.currentFocus
val imm = appCompatActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
通过将Generic方法添加到Utility或Helper类。通过调用自己,您可以隐藏和显示键盘
fun AppCompatActivity.hideKeyboard() {
val view = this.currentFocus
if (view != null) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
}
fun AppCompatActivity.showKeyboard() {
val view = this.currentFocus
if (view != null) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
} window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
}
Kotlin版本:
fun showKeyboard(mEtSearch: EditText, context: Context) {
mEtSearch.requestFocus()
val imm: InputMethodManager =
context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(mEtSearch, 0)
}
您可以使用InputMethodManager强制Android隐藏虚拟键盘,调用hideSoftInputFromWindow,传入包含焦点视图的窗口的标记。
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
这将在所有情况下强制隐藏键盘。在某些情况下,您需要将InputMethodManager.HIDE_IMPLICIT_ONLY作为第二个参数传递,以确保仅在用户未显式强制显示键盘时(通过按住菜单)隐藏键盘。
注意:如果您想在Kotlin中执行此操作,请使用:上下文getSystemService(Context.INPUT_METHOD_SERVICE)作为InputMethodManager
Kotlin语法
// Only runs if there is a view that is currently focused
this.currentFocus?.let { view ->
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.hideSoftInputFromWindow(view.windowToken, 0)
}