实现功能:点击EditText,软键盘出现并且不会隐藏,点击或者触摸EditText以外的其他任何区域,软键盘被隐藏;
1、重写dispatchTouchEvent()方法,获取当前触摸事件为DOWN的时候隐藏软键盘
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//Finger touch screen event
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
// get current focus,Generally it is EditText
View view = getCurrentFocus();
if (isShouldHideSoftKeyBoard(view, ev)) {
hideSoftKeyBoard(view.getWindowToken());
}
}
return super.dispatchTouchEvent(ev);
}
2、isShouldHideInput()方法;
private boolean isShouldHideSoftKeyBoard(View view, MotionEvent event) {
if (view != null && (view instanceof EditText)) {
int[] l = { 0, 0 };
view.getLocationInWindow(l);
int left = l[0], top = l[1], bottom = top +view.getHeight(), right = left
+ view.getWidth();
if (event.getX() > left && event.getX() < right
&& event.getY() > top && event.getY() < bottom) {
// If click the EditText event ,ignore it
return false;
} else {
return true;
}
}
// if the focus is EditText,ignore it;
return false;
}
3、hideSoftKeyBoard()方法;
private void hideSoftKeyBoard(IBinder token) {
if (token != null) {
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(token,
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
您可能感兴趣的文章:Android监听软键盘弹出与隐藏的两种方法Android软键盘的显示隐藏功能实现过程Android 软键盘弹出隐藏挤压界面等各种问题小结Android判断软键盘弹出并隐藏的简单完美解决方法(推荐)Android 显示和隐藏软键盘的方法(手动)Android键盘显示与隐藏代码解析android中隐藏与显示软键盘及不自动弹出键盘的实现方法Android 隐藏及切换显示键盘