Backlight87
8/24/2017 - 2:17 PM

手机软键盘相关,判断软键盘状态,显示软键盘,隐藏软键盘

手机软键盘相关,判断软键盘状态,显示软键盘,隐藏软键盘

public class KeyboardUtil {
    // 软键盘的状态
    /** 键盘在显示状态 */
    public static final String KEYBOARD_SHOW = "keyboard_show";
    /** 键盘隐藏状态 */
    public static final String KEYBOARD_HIDE = "keyboard_hide";

    /**
     * @title: checkKeyboardStatus
     * @description: 判断软键盘的状态
     * @return String
     * @throws
     */
    public static String checkKeyboardStatus(Activity activity) {
        final View v = activity.getWindow().peekDecorView();
        if (v != null && v.getWindowToken() != null) {
            return KEYBOARD_SHOW;
        }
        return KEYBOARD_HIDE;
    }

    /**
     * @describe:手动调用软键盘
     */
    public static void showKeyboard(Activity activity) {
        InputMethodManager manager =
            (InputMethodManager) activity.getBaseContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
        manager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public static void showKeyboard(View view, Activity activity) {
        InputMethodManager manager =
            (InputMethodManager) activity.getBaseContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
        manager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
    }

    /**
     * @describe:隐藏软键盘
     */
    public static void hideKeyboard(Activity activity) {
        if (activity != null && activity.getCurrentFocus() != null) {
            String status = KeyboardUtil.checkKeyboardStatus(activity);
            if (!KeyboardUtil.KEYBOARD_HIDE.equals(status)) {
                // 隐藏软键盘
                InputMethodManager manager =
                    (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
                if (manager != null) {
                    manager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
    }
}