[英]How to hide soft Keyboard without focus in Android?
我遇到這種情況,我檢查軟鍵盤是否打開,我想在代碼中關閉,當我使用下面的代碼時,它無法關閉鍵盤,因為代碼找不到任何焦點,但鍵盤仍然打開,所以我怎樣才能隱藏它?
private void hideSoftKeyboard() {
Activity activity = (Activity) sContext;
View view = activity.getCurrentFocus();
if (view != null) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
//((Activity) sContext).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
} else {
Log.i(sClassTag,"focus not found");
}
}
嘗試使用這個
您可以使用InputMethodManager
強制 Android 隱藏虛擬鍵盤,調用hideSoftInputFromWindow
,傳入包含焦點視圖的窗口的標記。
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
這將強制在所有情況下隱藏鍵盤。 在某些情況下,您可能希望將InputMethodManager.HIDE_IMPLICIT_ONLY
作為第二個參數傳遞,以確保僅在用戶沒有明確強制顯示鍵盤時才隱藏鍵盤(通過按住菜單)。
或這個
InputMethodManager imm =(InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
你可以在這里找到更多細節
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
您可以使用這些擴展來切換鍵盤:
fun Context.showKeyboard() {
val imm = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
}
fun Context.hideKeyboard() {
val imm = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY)
}
fun Context.toggleKeyboard() {
val imm = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
if (imm.isActive) {
hideKeyboard()
} else {
showKeyboard()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.