打开关闭软键盘,点击屏幕其他地方关闭软键
关闭然键盘:
public void closeKeyboard() {
View rootView = getWindow().getDecorView();
closeKeyboard(rootView);
}
public void closeKeyboard(View view) {
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
View v = getCurrentFocus();
if (v != null && im.isActive()) {
view.setFocusable(true);
view.setFocusableInTouchMode(true);
view.requestFocus();
im.hideSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
打开软键盘:
public void openKeyboard(View v) {
v.requestFocus();
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
im.showSoftInput(v, 0);
}
点击屏幕其他地方关闭然键盘:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (v != null) {
Log.e("v", "v = " + v.getClass().getSimpleName());
}
if (isShouldHideKeyboard(v, ev)) {
closeKeyboard();
}
}
return super.dispatchTouchEvent(ev);
}
/**
* 根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘,因为当用户点击EditText时则不能隐藏
*
* @param v
* @param event
* @return
*/
public boolean isShouldHideKeyboard(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
return !isTouchView(v, event);
}
// 如果焦点不是EditText则忽略,这个发生在视图刚绘制完,第一个焦点不在EditText上,和用户用轨迹球选择其他的焦点
return false;
}
//是不是点击在view上
public boolean isTouchView(View v, MotionEvent event) {
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;
}