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