美文网首页
android触摸界面隐藏软键盘&查看软键盘状态

android触摸界面隐藏软键盘&查看软键盘状态

作者: 鵬_875 | 来源:发表于2018-06-25 21:34 被阅读0次
    /**
     * 软键盘工具类
     */
    public class SoftInputUtil {
        // 软键盘是否弹出
        public static boolean isSoftShowing(Activity activity) {
            //获取当前屏幕内容的高度
            int screenHeight = activity.getWindow().getDecorView().getHeight();
            //获取View可见区域的bottom
            Rect rect = new Rect();
            activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
            return screenHeight - rect.bottom != 0;
        }
    
        // 隐藏软键盘
        public static void hideKeyboard(MotionEvent event, View focusView,
                                        Activity activity) {
    //        if (focusView == null || !(focusView instanceof EditText)) {
    //            return;
    //        }
            // 软键盘显示时才隐藏
            if (!SoftInputUtil.isSoftShowing(activity)) {
                return;
            }
            AppUtils.printLog("隐藏键盘");
            try {
                int[] location = {0, 0};
                focusView.getLocationInWindow(location);
                int left = location[0], top = location[1], right = left
                        + focusView.getWidth(), bottom = top + focusView.getHeight();
                // 判断焦点位置坐标是否在空间内,如果位置在控件外,则隐藏键盘
                if (event.getRawX() < left || event.getRawX() > right
                        || event.getY() < top || event.getRawY() > bottom) {
                    // 隐藏键盘
                    IBinder token = focusView.getWindowToken();
                    InputMethodManager inputMethodManager = (InputMethodManager) activity
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(token,
                            InputMethodManager.HIDE_NOT_ALWAYS);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:android触摸界面隐藏软键盘&查看软键盘状态

          本文链接:https://www.haomeiwen.com/subject/oysuyftx.html