在低版本上,如果啟動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之后,發(fā)現(xiàn)軟鍵盤沒有彈出來,也沒有焦點。
system_process E/InputMethodManagerService: SOFT_INPUT_STATE_ALWAYS_VISIBLE is ignored because there is no focused view that also returns true from View#onCheckIsTextEditor()
看了看源碼,然后百度了下看有沒有哥們已經(jīng)踩坑的,讓我發(fā)現(xiàn)了一篇
Android api 28 9.0 EditText無法自動彈出軟鍵盤(windowSoftInputMod stateAlwaysVisible targetSdkVersion)文章,這個哥們寫的很清晰詼諧.
解決:這個哥們有提到直接對控件進(jìn)行requestFocus,我這邊測試是可行的,可是,如果界面很復(fù)雜,復(fù)雜到你根本就不知道應(yīng)該哪個輸入框拿焦點呢?
我們需要找到第一個該拿到焦點的編輯框??梢允褂眠@個方法:
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已經(jīng)沒用了,有大佬知道為蝦米嗎?
2020/5/19 補(bǔ)充一下
有時候看代碼不是注解 真的是浪費(fèi)很多時間哎 ,
/**
* 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已經(jīng)失效了,除非在edit mode