Android 強制軟鍵盤關閉


  在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);
      }
    }
  }

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM