Make EditText ReadOnly

Viewed 198729

I want to make a read-only EditText view. The XML to do this code seems to be android:editable="false", but I want to do this in code.

How can I do this?

22 Answers

Use this code:

editText.setEnabled(false);
editText.setTextColor(ContextCompat.getColor(context, R.color.black);

Disabling editText gives a read-only look and behavior but also changes the text-color to gray so setting its text color is needed.

This was the only full simple solution for me.

editText.setEnabled(false);   // Prevents data entry
editText.setFocusable(false); // Prevents being able to tab to it from keyboard

As android:editable="" is deprecated,

Setting

  • android:clickable="false"
  • android:focusable="false"
  • android:inputType="none"
  • android:cursorVisible="false"

will make it "read-only".

However, users will still be able to paste into the field or perform any other long click actions. To disable this, simply override onLongClickListener().
In Kotlin:

  • myEditText.setOnLongClickListener { true }

suffices.

My approach to this has been creating a custom TextWatcher class as follows:

class ReadOnlyTextWatcher implements TextWatcher {
    private final EditText textEdit;
    private String originalText;
    private boolean mustUndo = true;

    public ReadOnlyTextWatcher(EditText textEdit) {
        this.textEdit = textEdit;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        if (mustUndo) {
            originalText = charSequence.toString();
        }
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (mustUndo) {
            mustUndo = false;
            textEdit.setText(originalText);
        } else {
            mustUndo = true;
        }
    }
}

Then you just add that watcher to any field you want to be read only despite being enabled:

editText.addTextChangedListener(new ReadOnlyTextWatcher(editText));
Related