Search code examples
androidandroid-preferencespreferenceactivity

How to make enter key work on EditTextPreference dialog


I gave android:singleLine="true" option on EditTextPreference, and when the edit box in the dialog has the focus, the software keyboard shows "Done" button in place of Enter key. However if I press the done button, only the software keyboard closes, and I still have to click Done button on the dialog.

Is there anyway to make enter key and ime action key on the software keyboard to close the dialog and apply the new value?


Solution

  • First, I set the IME Option to IME_ACTION_DONE

    mEditTextPreference.getEditText().setImeOptions(EditorInfo.IME_ACTION_DONE);
    

    and then using following code to save value and close dialog.

    mEditTextPreference.getEditText().setOnEditorActionListener(new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE){
                //mEditTextPreference.setText(mEditTextPreference.getEditText().getText().toString());
    
                //better solution
                mEditTextPreference.onClick(mEditTextPreference.getDialog(), Dialog.BUTTON_POSITIVE);
                mEditTextPreference.getDialog().dismiss();
                return true;
            }
            return false;
        }
    });