在Android開發過程中,有時候我們會有強制關閉軟鍵盤的需求。比如說:現在有一個文本編輯框(testEt)和一個按鈕(testBtn),我們現在點擊文本編輯框testEd,這時會彈出軟鍵盤,然后我們點擊按鈕testBtn,此時軟鍵盤還是保持了打開的狀態...問題來了,我們想要的結果是軟鍵盤消失。(testBtn只是我隨便舉的一個例子,也可以使別的控件例如下拉框、可點擊的圖片、自定義空間等等)
下面提供兩種方法解決:
一、這種方法只是關閉軟鍵盤:
在按鈕testBtn調用以下方法hideKeyboard():
private void hideKeyboard() {
InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive() && this.getCurrentFocus() != null) {
if (this.getCurrentFocus().getWindowToken() != null) {
imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
二、這種方法會線判斷軟鍵盤的狀態,如果時關閉狀態則打開,如果是打開狀態則關閉:
在按鈕testBtn調用以下方法hideKeyboard():
private void hideKeyboard() {
InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
if (this.getCurrentFocus().getWindowToken() != null) {
imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
