Android TextView setText() 与 append() 和 Editable.Factory

Android TextView setText() vs append() and Editable.Factory

要从 TextView 创建新的 Editable,您需要 Editable.Factory:

private final Editable.Factory editableFactory = new Editable.Factory() {
    @Override
    public Editable newEditable(CharSequence source) {
        Log.d("TAG", "newEditable() is called");
    }
};

myTextView.setEditableFactory(editableFactory);

我注意到 newEditable() 仅在调用 append() 时调用,但在调用 setText() 时不会调用,类似这样的事情:

myTextView.setText("some text");    // does not work
myTextView.append("some text");     // works

知道为什么会出现这种行为吗?谢谢

检查第 5731 行 TextView.java 中的附加方法:

Convenience method to append the specified text to the TextView's display buffer, upgrading it to {@link android.widget.TextView.BufferType#EDITABLE} if it was not already editable.

append(CharSequence text) 将调用 append(text, 0, text.length()),其中包含以下内容:

if (!(mText instanceof Editable)) {
    setText(mText, BufferType.EDITABLE);
}

setText(CharSequence text, BufferType type) 呼叫 setText(CharSequence text, BufferType type, boolean notifyBefore, int oldlen).
此方法包含一些 if 语句,这些语句将根据类型更改功能。
第 6156 行:

if (type == BufferType.EDITABLE || getKeyListener() != null || needEditableForNotification) {
    createEditorIfNeeded();
    mEditor.forgetUndoRedo();
    Editable t = mEditableFactory.newEditable(text);
    text = t;
    setFilters(t, mFilters);
    InputMethodManager imm = getInputMethodManager();
    if (imm != null) imm.restartInput(this);

因此,如果您愿意,您也应该可以使用 public void setText(CharSequence text, BufferType type)