Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 軟鍵盤控制:顯示、隱藏,以及如何阻止它自動彈出

編輯:關於 Android 程式設計

輸入法相關的操作看起來零碎,但幾乎每個有輸入框的 App 都會遇到。以下整理三個最常用的場景。

一、隱藏軟鍵盤

((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
        .hideSoftInputFromWindow(
                WidgetSearchActivity.this.getCurrentFocus().getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);

關鍵是取得目前焦點 View 的 windowToken。實務上建議先判空,因為使用者可能已經按下返回鍵或畫面正在切換,此時 getCurrentFocus() 會回傳 null:

InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
View focus = getCurrentFocus();
if (focus != null) {
    imm.hideSoftInputFromWindow(focus.getWindowToken(), 0);
}

二、主動顯示軟鍵盤

((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
        .showSoftInput(view, 0);

傳入的 View 可以是 EditText、TextView 等可輸入的控件。若希望畫面跳進來就自動聚焦並叫出鍵盤,記得該 View 必須是 focusableInTouchMode。

三、不要自動彈出鍵盤

帶有 EditText 的畫面第一次顯示時會自動取得焦點並彈出鍵盤,這在只需要「展示內容」的頁面上很惱人。有兩種解法。

方法一:在 Manifest 中設定 Activity 屬性

android:windowSoftInputMode="stateHidden"

或

android:windowSoftInputMode="stateUnchanged"

stateHidden 是「進入畫面時若鍵盤開著就收起來」,stateUnchanged 則是「保持原狀、不主動改變」。兩者差別在於是否要主動去關掉已經開啟的鍵盤。

方法二:把焦點搶走

在版面中放一個隱形的 TextView,於 onCreate() 時讓它 requestFocus():

<TextView
    android:id="@+id/text_notuse"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="true"
    android:focusableInTouchMode="true" />
TextView textView = (TextView) findViewById(R.id.text_notuse);
textView.requestFocus();

注意:這個 TextView 不要設成 android:visibility="gone",否則會失效。看不見又拿不到焦點的 View 無法承接焦點移轉;若真的不想佔位,改用 android:visibility="invisible",或乾脆用方法一。

補充:Fragment 與列表中的鍵盤

上述方法在 Activity 上最直接。若在 Fragment 中使用,getCurrentFocus() 要換成 getActivity().getCurrentFocus();在 RecyclerView 中切換頁面時,記得在 onViewRecycled 或離開畫面前主動收起鍵盤,否則容易出現「鍵盤還開著但頁面已經換了」的尷尬狀態。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved