背景:
项目中在登录界面里有
1、一个设置服务器地址的UI
2、一个修改密码的UI
但是设置了服务器成功后,软键盘也不会自动关闭,这样用户体验有些不够完美。
解决:
1、定位一个监控类
2、让监控类帮我们实时处理是否显示状态
3、根据状态,来处理软键盘让其显示或隐藏。
1、KeyBoardShowListener(来自:https://blog.csdn.net/qq_26446715/article/details/80674378)
public class KeyBoardShowListener { private Context ctx; public KeyBoardShowListener(Context ctx) { this.ctx = ctx; } OnKeyboardVisibilityListener keyboardListener; public OnKeyboardVisibilityListener getKeyboardListener() { return keyboardListener; } public interface OnKeyboardVisibilityListener { void onVisibilityChanged(boolean visible); } public void setKeyboardListener(final OnKeyboardVisibilityListener listener, Activity activity) { final View activityRootView = ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0); activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { private boolean wasOpened; private final int DefaultKeyboardDP = 100; // From @nathanielwolf answer... Lollipop includes button bar in the root. Add height of button bar (48dp) to maxDiff private final int EstimatedKeyboardDP = DefaultKeyboardDP + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 48 : 0); private final Rect r = new Rect(); @Override public void onGlobalLayout() { // Convert the dp to pixels. int estimatedKeyboardHeight = (int) TypedValue .applyDimension(TypedValue.COMPLEX_UNIT_DIP, EstimatedKeyboardDP, activityRootView.getResources().getDisplayMetrics()); // Conclude whether the keyboard is shown or not. activityRootView.getWindowVisibleDisplayFrame(r); int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top); boolean isShown = heightDiff >= estimatedKeyboardHeight; if (isShown == wasOpened) { Log.e("Keyboard state", "Ignoring global layout change..."); return; } wasOpened = isShown; listener.onVisibilityChanged(isShown); } }); } }
2、全局监控(Fragment中调用)
private void moniteKeyboard(){ new KeyBoardShowListener(getActivity()).setKeyboardListener( new KeyBoardShowListener.OnKeyboardVisibilityListener() { @Override public void onVisibilityChanged(boolean visible) { if (visible) { bKeyboardShow = true; } else { bKeyboardShow = false; } } }, getActivity()); }
说明:bKeyboardShow 全局变量
3、处理状态
if(bKeyboardShow){ hideKeyboard(); }
这样就可以了,在需要的地方加入
protected void hideKeyboard() { InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); }
说明:上面方法,显示的会隐藏,隐藏的时候会显示。