# kotlin 隱藏鍵盤搭配擴充函數 ## 紀錄一下使用EditText時,鍵盤隱藏的處理 ### 如圖所示,當EditText取得焦點後會自動跳出鍵盤,此時沒有手動把鍵盤關閉,執行取消的按鈕,會發生第二張圖片的狀況,鍵盤沒有自動隱藏 ![](https://i.imgur.com/cQUZe37.png) ![](https://i.imgur.com/T7h6i0Y.png) ### 使用擴充函數隱藏鍵盤 #### 在這個例子我是使用Dialog,在按下取消按鈕之後,先執行關閉鍵盤的函數,再把dailog畫面隱藏 ```kotlin= //以上省略 .setNeutralButton("取消"){ dialog, which -> hideKeyboard(mview) dialog?.dismiss() } fun Context.hideKeyboard(view: View) { val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0) } ``` ### 官方寫法 ```kotlin= // Hide the keyboard. val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0) ``` ###### tags: `kotlin` `Android` `Extension` `擴充函數`