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

/**
 * 软键盘工具类
 */
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();
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容