在低版本上,如果启动Activity/dialog想要自动焦点到编辑框,有很多种方式,其中一种是SOFT_INPUT_STATE_ALWAYS_VISIBLE
mDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN
| WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
在升级到Android9.0之后,发现软键盘没有弹出来,也没有焦点。
system_process E/InputMethodManagerService: SOFT_INPUT_STATE_ALWAYS_VISIBLE is ignored because there is no focused view that also returns true from View#onCheckIsTextEditor()
看了看源码,然后百度了下看有没有哥们已经踩坑的,让我发现了一篇
Android api 28 9.0 EditText无法自动弹出软键盘(windowSoftInputMod stateAlwaysVisible targetSdkVersion)文章,这个哥们写的很清晰诙谐.
解决:这个哥们有提到直接对控件进行requestFocus,我这边测试是可行的,可是,如果界面很复杂,复杂到你根本就不知道应该哪个输入框拿焦点呢?
我们需要找到第一个该拿到焦点的编辑框。可以使用这个方法:
private boolean mHasFoundFocus = false;
private void requestFocus(ViewGroup viewGroup) {
if (viewGroup == null ||mHasFoundFocus) {
return;
}
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View view = viewGroup.getChildAt(i);
if (view instanceof ViewGroup && View.VISIBLE == view.getVisibility()) {
requestFocus((ViewGroup) view);
} else if (view instanceof EditText) {
if (view.requestFocus()) {
mHasFoundFocus = true;
return;
}
}
}
}
其实最简单的还是要弄明白,android 9.0为什么要这么弄,这样操作之后是不是SOFT_INPUT_STATE_ALWAYS_VISIBLE已经没用了,有大佬知道为虾米吗?
2020/5/19 补充一下
有时候看代码不是注解 真的是浪费很多时间哎 ,
/**
* Visibility state for {@link #softInputMode}: please always make the
* soft input area visible when this window receives input focus.
*
* <p>Applications that target {@link android.os.Build.VERSION_CODES#P} and later, this flag
* is ignored unless there is a focused view that returns {@code true} from
* {@link View#isInEditMode()} when the window is focused.</p>
*/
public static final int SOFT_INPUT_STATE_ALWAYS_VISIBLE = 5;
这边注解明明白白清清楚楚的写着 在Android P已经失效了,除非在edit mode