Search code examples
androidandroid-edittexttextviewandroid-editable

What really happens when setText() is called on an EditText?


This is a part of the code:

editText.setText("Some Text", TextView.BufferType.EDITABLE);

Editable editable = (Editable) editText.getText();

// value of editable.toString() here is "Some Text"

editText.setText("Another Text", TextView.BufferType.EDITABLE);

// value of editable.toString() is still "Some Text"

Why the value of editable.toString() did not change? Thanks


Solution

  • You assigned editText.getText() to a variable. That means its value won't change.

    When you call setText(), the original text is overwritten with the new CharSequence; the original instance of the Editable that getText() returns is no longer part of the TextView, so your editable variable is no longer attached to the TextView.

    Take a look at TextView's getEditableText() (this is what EditText calls from getText()):

    public Editable getEditableText() {
        return (mText instanceof Editable) ? (Editable) mText : null;
    }
    

    If mText is an Editable Object, then it'll return it. Otherwise, it'll return null.

    setText() eventually makes its way to setTextInternal():

    private void setTextInternal(@Nullable CharSequence text) {
        mText = text;
        mSpannable = (text instanceof Spannable) ? (Spannable) text : null;
        mPrecomputed = (text instanceof PrecomputedText) ? (PrecomputedText) text : null;
    }
    

    As you can see, it just overwrites the mText field, meaning your Editable instance is no longer the instance that the EditText has.

    TextView.java