1

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

1 Answers1

2

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

TheWanderer
  • 16,775
  • 6
  • 49
  • 63
  • I agree with most of this answer, but simply assigning a value to a variable doesn't mean that the value will never change. `SpannableStringBuilder` implements `Editable`, and so the results of its `toString()` method can change over time. – Ben P. Nov 13 '18 at 15:46
  • @BenP. yes, but OP isn't using a SpannableStringBuilder. OP is using an EditText, which _does_ overwrite the variable returned by `getText()`. That means that the `editable` variable OP has won't change when `setText()` is called. – TheWanderer Nov 13 '18 at 15:50
  • My point is just that the blanket statement "You assigned X to a variable, therefore X's value won't change" is not true in general. It may be true in this case, but it would be a bad lesson to "learn" for java programming in general. – Ben P. Nov 13 '18 at 15:53
  • It wasn't meant as a blanket statement. – TheWanderer Nov 13 '18 at 15:54
  • ` Editable t = mEditableFactory.newEditable(text); text = t; ` also helped me a lot. Thanks – H. Riantsoa Nov 13 '18 at 16:54