使軟鍵盤消失的方法如下:
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);
}
}
}
大功告成!!!