1、常用工具类方法
/**
* 根据输入法的状态显示和隐藏输入法
*/
public static void autoInputmethod(Context context) {
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
/**
* 隐藏软键盘(只适用于Activity,不适用于Fragment)
*/
public static void hideSoftKeyboard(Activity activity) {
View view = activity.getCurrentFocus();
if (view != null) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
/**
* 隐藏软键盘(可用于Activity,Fragment)
*/
public static void hideSoftKeyboard(Context context, List<View> viewList) {
if (viewList == null) return;
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
for (View v : viewList) {
inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
/**
* 隐藏软键盘(可用于Activity,Fragment)
*/
public static void hideSoftKeyboard(Context context, View view) {
if (view == null) return;
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
2、处理特殊情况【例如Dialog隐藏输入框 可以重写dispatchTouchEvent,其它情况类似处理即可】
@Override
public boolean dispatchTouchEvent(
MotionEvent event){
if(event.getAction()== MotionEvent.ACTION_DOWN){
View v = getCurrentFocus();
if(v instanceof EditText){
Rect outRect = new Rect();
v.getGlobalVisibleRect(outRect);
if(!outRect.contains((int)event.getRawX(),(int)event.getRawY())){
v.clearFocus();
InputMethodManager imm =(InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(),0);
}
}
}
return super.dispatchTouchEvent(event);
}