原文發表於:blog.csdn.net/qq_27485935 , 你們沒事能夠去逛逛 (ง •̀_•́)งjava
在平時的 App 開發中, 免不了會遇到須要開發者隱藏軟鍵盤的狀況, 好比當在多個輸入框填入我的基本信息, 最後有個保存按鈕, 點擊便可將我的基本信息保存, 這時就須要開發者編寫代碼去隱藏軟鍵盤, 而不須要用戶本身去手動隱藏, 這樣大大提升 App 的用戶體驗。ide
public static void hideKeyboard() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}複製代碼
而試驗結果倒是...spa
當軟鍵盤顯示了, 調用上述方法確實能夠隱藏。 可是當軟鍵盤已經隱藏了, 調用上述方法後又將從新顯示。.net
我在 StackOverflow 中逛了一圈, 最後試驗出兩個成功的方法, 以下:3d
public class SoftKeyboardUtil {
/** * 隱藏軟鍵盤(只適用於Activity,不適用於Fragment) */
public static void hideSoftKeyboard(Activity activity) {
View view = activity.getCurrentFocus();
if (view != null) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
/** * 隱藏軟鍵盤(可用於Activity,Fragment) */
public static void hideSoftKeyboard(Context context, List<View> viewList) {
if (viewList == null) return;
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
for (View v : viewList) {
inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}複製代碼
有人可能會問 SoftKeyboardUtil 第二個方法的 List<View> viewList
參數是什麼, viewList 中須要放的是當前界面全部觸發軟鍵盤彈出的控件。 好比一個登錄界面, 有一個帳號輸入框和一個密碼輸入框, 須要隱藏鍵盤的時候, 就將兩個輸入框對象放在 viewList 中, 做爲參數傳到 hideSoftKeyboard 方法中便可。code
原理待之後慢慢發掘......cdn