Android控制软键盘显示和隐藏的工具类

Android控制软键盘显示和隐藏的工具类

/**
 * <p>
 *     控制软键盘显示和隐藏的工具类
 * </p>
 */
public class KeyboardUtils {
    
    
     /**
     * 显示软键盘
     * @param editText
     */
    public static void showKeyboard(EditText editText) {
    
    
        InputMethodManager inputMethodManager = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        // 判空防止空指针
        if (inputMethodManager != null) {
    
    
            editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            // 请求获取焦点
            editText.requestFocus();
            inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 隐藏软键盘
     * @param editText
     */
    public static void hideKeyboard(EditText editText){
    
    
        InputMethodManager imm = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        // 判空防止空指针
        if (imm != null) {
    
    
        	// 清除焦点
            editText.clearFocus();
            imm.hideSoftInputFromWindow(editText.getWindowToken(),0);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/C_biubiubiu/article/details/109779803
今日推荐