兩個問題:
- AlertDialog 中默認選中 EditText 焦點,并且彈出軟鍵盤
- AlertDialog 中 EditText 無法彈出軟鍵盤
兩個問題都在不同場景出現(xiàn)過;
對于第一個問題:
業(yè)務(wù)場景是使用繪制的鍵盤布局替代系統(tǒng)的軟鍵盤,這時候需要阻止系統(tǒng)軟鍵盤的彈出:EditText.setShowSoftInputOnFocus(false)
然而當 AlertDialog.show() 之后軟鍵盤自動彈出,推測是 AlertDialog 加載時可能會根據(jù)子 View 去調(diào)用 InputMethodManager 導致的(誤)。
之后就找到 AlertDialog 中的一段注釋:
* <p>The AlertDialog class takes care of automatically setting
* {@link android.view.WindowManager.LayoutParams#FLAG_ALT_FOCUSABLE_IM
* WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM} for you based on whether
* any views in the dialog return true from {@link View#onCheckIsTextEditor()
* View.onCheckIsTextEditor()}. Generally you want this set for a Dialog
* without text editors, so that it will be placed on top of the current
* input method UI. You can modify this behavior by forcing the flag to your
* desired mode after calling {@link #onCreate}
提到了 FLAG_ALT_FOCUSABLE_IM ,flag 讓 AlertDialog 的子 View. onCheckIsTextEditor() return true 以此讓彈窗在最近的輸入框 UI 上面,但是這種情況是默認了彈窗中沒有輸入框;
然后 Dialog 中也標注:
* <p>Often you will want to have a Dialog display on top of the current
* input method, because there is no reason for it to accept text. You can
* do this by setting the {@link WindowManager.LayoutParams#FLAG_ALT_FOCUSABLE_IM
* WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM} window flag (assuming
* your Dialog takes input focus, as it the default) with the following code:
*
* <pre>
* getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
* WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);</pre>
兩段注釋都表明 flag FLAG_ALT_FOCUSABLE_IM 決定了 Dialog 和 軟鍵盤之間的交互。
所以回到開頭提到的兩個問題都可以通過設(shè)置 / 清除 FLAG 實現(xiàn):
// 阻止軟鍵盤自動彈出
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
// 解決 EditText 無法彈出軟鍵盤
getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);