18

I am using an EditText. Is it possible to have a part of text uneditable and the rest editable in the same EditText?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Sam97305421562
  • 3,027
  • 10
  • 35
  • 45

2 Answers2

16

You could use

editText.setFocusable(false);

or

editText.setEnabled(false);

although disabling the EditText does currently not ignore input from the on-screen keyboard (I think that's a bug).

Depending on the application it might be better to use an InputFilter that rejects all changes:

editText.setFilters(new InputFilter[] {
    new InputFilter() {
        public CharSequence filter(CharSequence src, int start,
            int end, Spanned dst, int dstart, int dend) {
            return src.length() < 1 ? dst.subSequence(dstart, dend) : "";
        }
    }
});

Also see this question.

Community
  • 1
  • 1
Josef Pfleger
  • 74,165
  • 16
  • 97
  • 99
  • 2
    For show/hide password fields, the text content is cleared if you use this trick and then change the input type (`editText.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD)`). The workaround is to temporarily set the filters to the empty array while you change the input type. – David Leonard Nov 11 '10 at 09:28
2

You can implement a TextChangedListener where you make sure those parts of your text wont get deleted/overwritten.

class TextChangedListener implements TextWatcher {
    public void afterTextChanged(Editable s) {
                makeSureNothingIsDeleted();
    }

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    public void onTextChanged(CharSequence s, int start, int before, int count) {}
}

    TextChangedListener tcl = new TextChangedListener();
    my_editable.addTextChangedListener(tcl);
Nikhil
  • 16,194
  • 20
  • 64
  • 81
Ulrich Scheller
  • 11,800
  • 5
  • 28
  • 32