今天做项目的时候,做个搜索商品的功能,发现点击软键盘的回车后软键盘并不能自动隐藏,上网查了下,发现方法很多,但是能够同时兼容fragment和activity的并不多。去StackOverflow 溜达一圈,发现了两个解决方案
public class hidesoftboard{
/**
* 隐藏软键盘(只适用于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);
}
}
}