兩個(gè)問題:
- AlertDialog 中默認(rèn)選中 EditText 焦點(diǎn),并且彈出軟鍵盤
- AlertDialog 中 EditText 無法彈出軟鍵盤
兩個(gè)問題都在不同場景出現(xiàn)過挎峦;
對于第一個(gè)問題:
業(yè)務(wù)場景是使用繪制的鍵盤布局替代系統(tǒng)的軟鍵盤,這時(shí)候需要阻止系統(tǒng)軟鍵盤的彈出:EditText.setShowSoftInputOnFocus(false)
然而當(dāng) AlertDialog.show() 之后軟鍵盤自動(dòng)彈出妻坝,推測是 AlertDialog 加載時(shí)可能會(huì)根據(jù)子 View 去調(diào)用 InputMethodManager 導(dǎo)致的(誤)。
之后就找到 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 上面刽宪,但是這種情況是默認(rèn)了彈窗中沒有輸入框;
然后 Dialog 中也標(biāo)注:
* <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 和 軟鍵盤之間的交互界酒。
所以回到開頭提到的兩個(gè)問題都可以通過設(shè)置 / 清除 FLAG 實(shí)現(xiàn):
// 阻止軟鍵盤自動(dòng)彈出
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
// 解決 EditText 無法彈出軟鍵盤
getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);