使软键盘消失的方法如下:
public static void hintKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive() && activity.getCurrentFocus() != null) {
if (activity.getCurrentFocus().getWindowToken() != null) {
imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
点击空白地方使输入框消失代码如下可以在activity中重写onTouchEvent:
// 点击空白区域 自动隐藏软键盘
public boolean onTouchEvent(MotionEvent event) {
if(null != this.getCurrentFocus()){
/**
* 点击空白位置 隐藏软键盘
*/
InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
}
return super .onTouchEvent(event);
}
在fragment中由于没有onTouchEvent重写所以可以在onCreateView中,对view使用以下方法:
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
InputMethodManager manager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if(event.getAction() == MotionEvent.ACTION_DOWN){
if(getActivity().getCurrentFocus()!=null && getActivity().getCurrentFocus().getWindowToken()!=null){
manager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
return false;
}
});
或者在activity中重写onTouchEvent然后在fragment中调用如下方法:
view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
getActivity().onTouchEvent(event);
return false;
}
});
上面的问题都不大,但是当你的activity或者fragment中包含scrollview的时候,你会发现你的onTouchEvent()根本不会得到调用,这个时候你就慌了,接着你会去想方法设法的实现touch,click,focus监听,然而你会发现然并卵,你就会去思考,能不能重写scrollview来拦截touch事件,然而你会发现仍然是然并卵,那么到底如何解决呢?
步骤如下
1、设置一个公共的方法 用来隐藏软键盘
public static void hintKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive() && activity.getCurrentFocus() != null) {
if (activity.getCurrentFocus().getWindowToken() != null) {
imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
2、在BaseActivity中或者BaseFragment中这样来调用:
/**
* 设置点击软键盘之外区域,软键盘消失
*
* @param view
*/
public void setHintKeyboardView(View view) {
if (!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
hintKeyboard(getActivity());
return false;
}
});
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setHintKeyboardView(innerView);
}
}
}
大功告成!!!