[Android] Hide Keyboard

記錄一下隱藏軟鍵盤遇到的問題與解決方法

有一個頁面裡面有 EditText,第一次進入頁面的時候,要根據某些條件判斷要不要跳出鍵盤。

我期望的做法是,進入該頁面後判斷條件,如果不需要跳出鍵盤,那就 focus 在 RootView (ConstraintLayout) 上面並使用隱藏鍵盤的方法。

首先在 RootView (XML) 上面要設定兩種屬性

android:focusable="true"
android:focusableInTouchMode="true"

這樣 RootView 才能被設 focus

再來是呼叫隱藏鍵盤的方法

fun hideSoftInput(activity: Activity) {
    val inputMethodManager: InputMethodManager? = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    var view = activity.currentFocus
    if (view == null) view = View(activity)
    inputMethodManager?.hideSoftInputFromWindow(view.windowToken, 0)
}

記住,該 Activity 的 windowSoftInputMode (AndroidManifest.xml) 屬性不能設定為 `stateAlwaysVisible` ,不然透過以上設定還是會跳出鍵盤。

 

 

參考:

https://stackoverflow.com/questions/1555109/how-to-stop-edittext-from-gaining-focus-at-activity-startup-in-android