首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android AlertDialog EditText 自動彈出軟鍵盤:setSoftInputMode 解決方案

     編輯:程式設計綜合問答

AlertDialog 顯示時 EditText 雖獲焦點但軟鍵盤不自動彈出,需對話框視窗設定 SOFT_INPUT_STATE_ALWAYS_VISIBLE。關鍵在於對話框完全顯示後(onShow 或 onFocusChange)再設定。

方案一:OnShowListener(最可靠)


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 OnFocusChangeListener


editText.setOnFocusChangeListener((v, hasFocus) -> {
    if (hasFocus && dialog != null && dialog.isShowing()) {
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }
});

方案三:XML 主題預設(適用全域)





// 使用
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"

現代替代:BottomSheetDialogFragment


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 鍵盤不彈出問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved