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

Android 對話框彈出時自動顯示軟鍵盤的實現方法

     編輯:程式設計疑難解答

需求

點擊事件觸發對話框顯示的同時,自動彈出軟鍵盤,讓用戶直接輸入文字。

核心代碼

InputMethodManager inputMethodManager = (InputMethodManager) 
    getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);

完整範例

// 在點擊監聽器或對話框顯示後調用
Button btn = findViewById(R.id.btn_show_dialog);
btn.setOnClickListener(v -> {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    final EditText input = new EditText(this);
    builder.setView(input);
    AlertDialog dialog = builder.create();
    dialog.show();
    
    // 關鍵:對話框顯示後,請求焦點並顯示軟鍵盤
    input.requestFocus();
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(input, InputMethodManager.SHOW_IMPLICIT);
});

注意事項

  • `view` 參數必須是**可編輯且已獲取焦點**的視圖(如 `EditText`)。
  • `SHOW_IMPLICIT` 表示隱式顯示,不會強制覆蓋用戶設定。
  • 若在 `DialogFragment` 中,建議在 `onStart()` 或 `onResume()` 中調用,確保視圖已附著。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved