Why TextView getText() not instance of Spannable

有这样一个问题,调用TextViewsetText(CharSequence text)方法设置一个SpannableString,但是通过getText()得到的mText并不是SpannableString的实例, 而是一个SpannedString对象。查看TextView的源码发现,setText(CharSequence text)最终会调用下面的 setText()方法,mBufferType的默认值是BufferType.NORMAL,走到最后一个if else分支里,所以最后会调用TextUtilsstringOrSpannedString方法。

private void setText(CharSequence text, BufferType type,
                         boolean notifyBefore, int oldlen) {
  ...
if (type == BufferType.EDITABLE || getKeyListener() != null
                || needEditableForNotification) {
            ...
        } else if (precomputed != null) {
            ...
        } else if (type == BufferType.SPANNABLE || mMovement != null) {
            text = mSpannableFactory.newSpannable(text);
        } else if (!(text instanceof CharWrapper)) {
            text = TextUtils.stringOrSpannedString(text);
        }
}
复制代码

在这个函数里可以看到只要是Spanned的对象都会被转成SpannedString,这个SpannedString被赋值给mText

public static CharSequence stringOrSpannedString(CharSequence source) {
        if (source == null)
            return null;
        if (source instanceof SpannedString)
            return source;
        if (source instanceof Spanned)
            return new SpannedString(source);

        return source.toString();
    }
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享