package com.beanpodtech.allinone.utils;

import android.app.Activity;
import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

/**
 * 软键盘操作类
 */

public class SoftInputUtil {

    /**
     * 隐藏软键盘
     */
    public static boolean hideSoftInput(Activity context) {

        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            return imm.hideSoftInputFromWindow(context.getWindow().getDecorView().getWindowToken(), 0);
        }

        return false;
    }

    /**
     * 判断键盘是否可见
     *
     * @param v
     * @return true 可见 false 不可见
     */
    public static boolean ifSoftInputActive(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        return imm.isActive();
    }

    /**
     * 判断当前点击屏幕的地方是否是软键盘：
     *
     * @param v
     * @param event
     * @return true 是 false 不是
     */
    public static boolean ifShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            v.getLocationInWindow(leftTop);
            int left = leftTop[0], top = leftTop[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

}
