如何合并一些可跨越的对象?
我将一个可跨越的对象分为3部分,执行不同的操作,然后我需要合并它们。
Spannable str = editText.getText();
Spannable selectionSpannable = new SpannableStringBuilder(str, selectionStart, selectionEnd);
Spannable endOfModifiedSpannable = new SpannableStringBuilder(str, selectionEnd, editText.getText().length());
Spannable beginningOfModifiedSpannable = new SpannableStringBuilder(str, 0, selectionStart);
我该怎么做呢?我还没有找到所需的方法或构造函数来执行此操作。
I divide a spannable object into 3 parts, do different operations, and then I need to merge them.
Spannable str = editText.getText();
Spannable selectionSpannable = new SpannableStringBuilder(str, selectionStart, selectionEnd);
Spannable endOfModifiedSpannable = new SpannableStringBuilder(str, selectionEnd, editText.getText().length());
Spannable beginningOfModifiedSpannable = new SpannableStringBuilder(str, 0, selectionStart);
How can I do it? I haven't found the required method or constructor to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用:
http: //developer.android.com/reference/android/text/TextUtils.html#concat(java.lang.CharSequence...)
You could use this:
http://developer.android.com/reference/android/text/TextUtils.html#concat(java.lang.CharSequence...)
谢谢,它有效。我注意到我甚至可以合并 3 个可跨越的对象:
Thanks, it works. I have noticed that I can merge even 3 spannable object:
我知道这已经很旧了。但在稍微修改 kotlin stdlib 之后,我得到了这段代码:
希望它可以帮助某人。
I know this is old. But after modifying kotlin stdlib a bit I've got this code:
Hope it might help somebody.
使用SpannableStringBuilder。
更好的是,创建一个 kotlin 运算符重载:
只需将其作为顶级函数放入任何 kotlin 文件中即可。
您可以使用
+
连接:Use
SpannableStringBuilder
.Even better- make a kotlin operator overload:
just throw that in any kotlin file as a top level function.
and the you can concatenate using
+
:正如 marwinXXII 在评论中所说,使用 TextUtils.concat 确实有效,但在某些情况下,当单个
CharSequence
中有相同跨度的多个实例时,可能会导致样式丢失。解决方法是将
CharSequence
写入Parcel
,然后将其读回。执行此操作的示例 Kotlin 扩展代码如下:此代码的示例用法:
现在您可以连接大量
CharSequences
而不必担心丢失任何样式和格式!请注意,这适用于大多数样式,它并不总是有效,但应该足以涵盖所有基本样式。
As marwinXXII said in a comment, using
TextUtils.concat
does work but can cause loss of styles in some cases when you have multiple instances of the same span in a singleCharSequence
.A workaround could be to write the
CharSequence
to aParcel
and then read it back. Example Kotlin extension code to do this below:Example usage of this code:
Now you can concatenate tons of
CharSequences
without worrying about losing any of the styles and formatting you have on them!Note that this will work for most styles, it doesn't work all the time but should be enough to cover all the basic styles.