Android 強制軟鍵盤關閉

來源:互聯網
上載者:User

標籤:

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

 

  

Android 強制軟鍵盤關閉

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.