AlertDialog 顯示時 EditText 雖獲焦點但軟鍵盤不自動彈出,需對話框視窗設定 SOFT_INPUT_STATE_ALWAYS_VISIBLE。關鍵在於對話框完全顯示後(onShow 或 onFocusChange)再設定。
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("輸入名稱")
.setView(editText)
.setPositiveButton("確定", null)
.create();
dialog.setOnShowListener(d -> {
// 對話框顯示後立即設定
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
});
dialog.show();
// 確保 EditText 可獲焦點
editText.requestFocus();
editText.setOnFocusChangeListener((v, hasFocus) -> {
if (hasFocus && dialog != null && dialog.isShowing()) {
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
});
// 使用
AlertDialog dialog = new AlertDialog.Builder(this, R.style.DialogWithKeyboard)
.setView(editText)
.create();
public void showInputDialog() {
View view = LayoutInflater.from(this).inflate(R.layout.dialog_input, null);
EditText editText = view.findViewById(R.id.editText);
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("設定暱稱")
.setView(view)
.setPositiveButton("儲存", (d, which) -> {
String text = editText.getText().toString();
// 處理輸入
})
.setNegativeButton("取消", null)
.create();
dialog.setOnShowListener(d -> {
editText.requestFocus();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
});
dialog.show();
}
| 現象 | 原因 | 解決 |
|---|---|---|
| 鍵盤彈出又立即收回 | 多處設定 SoftInputMode 衝突 | 統一在 onShowListener 設定一次 |
| EditText 無焦點 | 佈局中其他視圖搶焦點 | editText.requestFocus() + editText.setFocusableInTouchMode(true) |
| 全螢幕 Dialog 鍵盤遮擋 | 未設定 windowSoftInputMode adjustResize | 主題加入 android:windowSoftInputMode="adjustResize" |
class InputBottomSheet : BottomSheetDialogFragment() {
override fun onCreateView(inflater, container, savedInstanceState): View? {
return inflater.inflate(R.layout.dialog_input, container, false)
}
override fun onViewCreated(view, savedInstanceState) {
val editText = view.findViewById(R.id.editText)
editText.requestFocus()
// BottomSheet 自動處理鍵盤彈出與 adjustResize
}
}
掌握 setOnShowListener + SOFT_INPUT_STATE_ALWAYS_VISIBLE 模式,即能可靠解決 AlertDialog 鍵盤不彈出問題。