參考
1、Android打開關閉軟鍵盤
2、android 滑動或者點擊其他地方隱藏鍵盤的方法
3、android中ScrollView的setOnClickListener無效
使用
1、SomeActivity extends BaseActivity
//父控件resid,如果有scrollview是子控件但是match_parent的話用scrollview的resid
hideParentSoftKeyborad(R.id.sv_batch_review);
2、BaseActivity
/**
* 點擊空白處或滑動時候隱藏軟鍵盤
* parent裏面下如果有scrollview佔據整個畫面的話,必須resLayout=scrollview_resid,不然監聽不到
* */
protected void hideParentSoftKeyborad(int resLayout){
//以前的:點空白處隱藏軟鍵盤
// findViewById(resLayout).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// LogUtil.d("===hideParentSoftKeyborad = onClick");
// AppUtil.hideSoftKeyboard(instance);
// }
// });
findViewById(resLayout).setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
AppUtil.hideSoftKeyboard(instance);
break;
case MotionEvent.ACTION_MOVE:
AppUtil.hideSoftKeyboard(instance);
break;
}
return false;
}
});
}
3、AppUtil
/**
* 關閉該控件的軟鍵盤
* */
public static void closeKeyBoard(Context ctx,EditText editText) {
try {
InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* 隱藏軟鍵盤
* */
public static void hideSoftKeyboard(Activity act){
InputMethodManager manager = (InputMethodManager) act.getSystemService(Activity.INPUT_METHOD_SERVICE);
View focus = act.getCurrentFocus();
manager.hideSoftInputFromWindow(
focus == null ? null : focus.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
public static void hideSoftKeyboard(IBinder token, Context context){
InputMethodManager inputMethodManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
}
4、ScrollView的坑!!!
1、一般來說直接傳parent_resid就可以了。但是!!!
2、scrollview不能onclick監聽,但是要監聽他的點擊和滑動就得用ontouch監聽
3、如果parent下有個差不多佔據整個屏幕的scrollview請傳scrollview_resid比較好,因爲parent_resid被遮擋了,監聽不到。。。