在我们的开发当中,为了使用户有更好的体验,有时需要手动回收键盘。
下面我总结了两种回收键盘的方法:
1、点击事件回收:
(1)Activity中:
InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(this.getWindow().getDecorView().getWindowToken(), 0);
}
(2)Fragment中:
UsingActivity usingActivity = (UsingActivity )getActivity();
InputMethodManager imm = (InputMethodManager)usingActivity .getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(usingMain.getWindow().getDecorView().getWindowToken(),0);
}
2、 点击空白处回收:
@Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN){
if(getCurrentFocus()!=null && getCurrentFocus().getWindowToken()!=null){
manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
return super.onTouchEvent(event);
}