Make EditText ReadOnly

前端 未结 22 1324

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.

H

22条回答
  •  醉话见心
    2020-12-04 19:14

    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));
    

提交回复
热议问题