背景
【Android】文本输入框弹出的同时软键盘也弹出,不需要点击两次才弹出软键盘window.setSoftInputMode解决
之前对软键盘操作,实现对点击输入框出现软键盘(即手机默认的键盘)
现在有一个需求是:
软键盘收起的时候,咱的输入框UI也消失
具体实现
// 键盘也跟着弹出来
mEtInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
//不论有没有focus就可得弹出键盘
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
inputMethodManager = (InputMethodManager) mEtInput.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(mEtInput, InputMethodManager.RESULT_UNCHANGED_SHOWN);
}
});
getActivity().getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener);
}
private ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
//只要视图有变化要求输入框focus以便弹出键盘
mEtInput.requestFocus();
//保证键盘和输入框同起同降
Insets insets = ViewCompat.getRootWindowInsets(getActivity().getWindow().getDecorView()).getInsets(WindowInsetsCompat.Type.ime());
if (0 == (insets.top - insets.bottom)) {
dismiss();
}
}