隐藏软键盘
/**
* 根据传入控件的坐标和用户的焦点坐标,判断是否隐藏键盘,如果点击的位置在控件内,则不隐藏键盘
*
* @param view 控件view
* @param event 焦点位置
*/
public static void hideKeyboard(MotionEvent event, View view, Activity activity) {
try {
if (view != null && view instanceof EditText) {
int[] location = {0, 0};
view.getLocationInWindow(location);
int left = location[0], top = location[1], right = left
+ view.getWidth(), bootom = top + view.getHeight();
// 判断焦点位置坐标是否在空间内,如果位置在控件外,则隐藏键盘
if (event.getRawX() < left || event.getRawX() > right
|| event.getY() < top || event.getRawY() > bootom) {
// 隐藏键盘
IBinder token = view.getWindowToken();
InputMethodManager inputMethodManager = (InputMethodManager) activity
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(token,
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
父类重写dispatchTouchEvent
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
View view = getCurrentFocus();
UtilHelper.hideKeyboard(ev, view, BaseActivity.this);//调用方法判断是否需要隐藏键盘
break;
default:
break;
}
return super.dispatchTouchEvent(ev);
}
2、在Activity里调用
/**
* 隐藏软键盘(只适用于Activity,不适用于Fragment)
*/
public static void hideSoftKeyboard(Activity activity) {
View view = activity.getCurrentFocus();
if (view != null) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
网友评论