Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

彈出輸入框並自動全選預設值,順手把輸入法叫出來

編輯:關於 Android 程式設計

「點開編輯既有資料」是很常見的互動。使用者通常希望三件事同時發生:游標在欄位裡、內容全被選取(可以直接打字覆蓋)、鍵盤立刻出現。這三件事各自不難,順序才是關鍵。

全選:selectAll() 要放在 show() 之後

final EditText input = new EditText(this);
input.setText("XXX");

new AlertDialog.Builder(this)
        .setView(input)
        .setTitle("編輯")
        .setPositiveButton("確定", null)
        .show();

input.selectAll();

為什麼順序重要?因為 selectAll() 依賴 EditText 已經具備有效的 Selection 狀態。在 Dialog 尚未 show() 之前呼叫,元件還沒完成版面配置,選取範圍可能無法正確套用。放在 show() 之後,就穩定了。

完整版本:全選 + 自動彈出鍵盤

把 selectAll() 與焦點監聽結合起來:

final AlertDialog dialog = new AlertDialog.Builder(this)
        .setView(editText)
        .setPositiveButton("確定", null)
        .create();

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            dialog.getWindow().setSoftInputMode(
                    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }
});

dialog.show();
editText.selectAll();

透過 OnFocusChangeListener 設定軟鍵盤模式,能確保鍵盤在欄位取得焦點的那一刻被叫出來,而不是等使用者再點一次。

更簡潔的寫法

其實不必繞這麼一圈。Window 的軟鍵盤模式可以直接在建立 Dialog 時設定:

final EditText editText = new EditText(this);
editText.setText("XXX");
editText.setSelectAllOnFocus(true);   // 取得焦點時自動全選

AlertDialog dialog = new AlertDialog.Builder(this)
        .setView(editText)
        .setPositiveButton("確定", null)
        .create();

dialog.setOnShowListener(new DialogInterface.OnShowListener() {
    @Override
    public void onShow(DialogInterface d) {
        // Dialog 顯示後才設定鍵盤模式,確保生效
        dialog.getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE
                | WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        editText.requestFocus();
    }
});

dialog.show();

這裡有兩個更省事的地方:setSelectAllOnFocus(true) 是 EditText 內建的屬性,等價於 XML 裡的 android:selectAllOnFocus="true",不需要手動呼叫 selectAll();而 setOnShowListener 比 OnFocusChangeListener 更直接,因為我們真正想 hook 的時機是「Dialog 顯示的那一刻」。

幾個實務細節

requestFocus() 是必要的

Dialog 顯示後,焦點預設在「確定」按鈕上。若不呼叫 editText.requestFocus(),即使設了鍵盤模式也可能不會彈出,因為焦點不在 EditText 上。

鍵盤模式的常數怎麼選

  • SOFT_INPUT_STATE_VISIBLE:只要有可能就顯示鍵盤。
  • SOFT_INPUT_STATE_ALWAYS_VISIBLE:無論使用者之前是否手動收起鍵盤,都強制顯示。適合明確要求輸入的場景。
  • SOFT_INPUT_ADJUST_RESIZE:鍵盤出現時縮放版面,避免輸入框被遮住。

兩者可用位元或運算組合。

注意版面被鍵盤擋住

若 Dialog 內有多個欄位,鍵盤彈出可能遮住下方內容。在 Activity 的 manifest 中設定 android:windowSoftInputMode="adjustResize",或為 Dialog 的版面加上ScrollView,都能改善。

顯示後再定位游標

若需要把游標移到特定位置而非全選,用 editText.setSelection(index),同樣建議放在 show() 之後或 onShowListener 裡。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved