关于软键盘弹出与隐藏

//弹起键盘
public static void showKeyboard(View view) {
InputMethodManager imm = (InputMethodManager) view.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
view.requestFocus();
imm.showSoftInput(view, 0);
}
}

//隐藏软键盘
public static void hideKeyboard(View view){
InputMethodManager imm = (InputMethodManager)view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null){
imm.hideSoftInputFromWindow(view.getWindowToken(),0);
}
}

检测软键盘是否显示的类
public class UIUtils {

/**
 * 判断键盘是否显示
 * @param activity
 * @return
 */
public static boolean isSoftShowing(Activity activity) {
    //获取当前屏幕内容的高度
    int screenHeight = activity.getWindow().getDecorView().getHeight();
    //获取View可见区域的bottom
    Rect rect = new Rect();
    activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
    int bottom = rect.bottom;
    return screenHeight - rect.bottom > screenHeight/3;
}

/**
 * 如果键盘弹出则隐藏键盘
 * @param activity
 */
public static void hideSoftKeyboard(Activity activity){
    if (isSoftShowing(activity)){
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }
}

/**
 * 显示软键盘
 * @param activity
 */
public static void showSoftKeyboard(Activity activity){
    if (!isSoftShowing(activity)){
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }
}


public interface OnSoftKeyWordShowListener {
    void hasShow(boolean isShow);
}
/**
 * 判断软键盘是否弹出
 * * @param rootView
 *
 * @param listener 备注:在不用的时候记得移除OnGlobalLayoutListener
 */
public static ViewTreeObserver.OnGlobalLayoutListener doMonitorSoftKeyWord(final View rootView, final OnSoftKeyWordShowListener listener) {
    final ViewTreeObserver.OnGlobalLayoutListener layoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            final Rect rect = new Rect();
            rootView.getWindowVisibleDisplayFrame(rect);
            final int screenHeight = rootView.getRootView().getHeight();

            final int heightDifference = screenHeight - rect.bottom;
            boolean visible = heightDifference > screenHeight / 3;
            if (listener != null)
                listener.hasShow(visible);
        }
    };
    rootView.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);
    return layoutListener;
}

}

上一篇:android studio 点击布局文件隐藏弹出的键盘。


下一篇:js prepend方法,添加下拉选