隐藏系统软键盘工具类

来源:互联网 发布:市场数据 编辑:程序博客网 时间:2024/06/07 01:49

public class KeyboardUtil {

/** * 根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘,因为当用户点击EditText时则不能隐藏 * * @param v * @param event * @return */public static boolean isShouldHideKeyboard(View v, MotionEvent event) {    if (v != null && (v instanceof EditText)) {        int[] l = {0, 0};        v.getLocationInWindow(l);        int left = l[0],                top = l[1],                bottom = top + v.getHeight(),                right = left + v.getWidth();        return !(event.getX() > left && event.getX() < right                && event.getY() > top && event.getY() < bottom);    }    // 如果焦点不是EditText则忽略,这个发生在视图刚绘制完,第一个焦点不在EditText上,和用户用轨迹球选择其他的焦点    return false;}/** * 获取InputMethodManager,隐藏软键盘 * * @param token */public static void hideKeyboard(Activity context, IBinder token) {    if (token != null) {        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);        imm.hideSoftInputFromWindow(token,0);    }}/** * 获取InputMethodManager,隐藏软键盘 * * @param token */public static void hideKeyboard(Activity context, IBinder token,int flags) {    if (token != null) {        InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);        im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);    }}public static void showKeyBoard(Activity activity, View view){    if(activity != null && view != null) {        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);    }}/** * 关闭键盘 * @param context */public static void closeSoftKeyBoard(Activity context){    View view = context.getWindow().peekDecorView();    if (view != null)    {        InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);    }}/** * 打开键盘 * @param context */public static void openSoftKeyBoard(Activity context){    InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);}

}

原创粉丝点击