原文地址:http://www.oschina.net/code/snippet_2329969_46958
方法1: 简单但有时会无效
InputMethodManager manager= (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
@Override
public
boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
if(getCurrentFocus()!=null&& getCurrentFocus().getWindowToken()!=null){
manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
return
super.onTouchEvent(event);
}
方法2: 完美适用activity与fragment
@Override
publicbooleandispatchTouchEvent(MotionEvent ev) {
if(ev.getAction() == MotionEvent.ACTION_DOWN) {
View view = getCurrentFocus();
if(isHideInput(view, ev)) {
HideSoftInput(view.getWindowToken());
}
}
returnsuper.dispatchTouchEvent(ev);
}
privatebooleanisHideInput(View v, MotionEvent ev) {
if(v !=null
&& (v instanceof
EditText)) {
int[] l = {0,0};
v.getLocationInWindow(l);
intleft = l[0], top
= l[1], bottom = top + v.getHeight(), right = left
+ v.getWidth();
if(ev.getX() > left && ev.getX() < right && ev.getY() > top
&& ev.getY() < bottom) {
//判断点击处与EditText距离
returnfalse;
}else{
returntrue;
}
}
returnfalse;
}
privatevoidHideSoftInput(IBinder token) {
if(token !=null) {
InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
manager.hideSoftInputFromWindow(token,
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
方法3、你可以强制android隐藏虚拟键盘,用InputMethodManager方法,调用hideSoftInputFromWindow。
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
这样可以强制在任何条件下隐藏虚拟键盘。