我正在尝试扩展一些跨度,以便它们可能成为复合的(以避免必须在一段文本上设置多个跨度),和/或存储有关它们自身的更多信息(例如“类型”和“ID”,等)
一切都按预期进行,直到我复制/剪切,然后粘贴文本。粘贴操作后,自定义跨度将丢失所有自定义设置,仅保留基本跨度特定样式。
例如,如果我扩展 BackgroundColorSpan
始终应用红色文本颜色,它会起作用。设置以下Extended BackgroundColorSpan
任何文本都会正确设置背景,并且文本将根据需要为红色。这是跨度的代码:
public class ExtendedBackgoundColorSpan extends BackgroundColorSpan {
private final int fgColor = Color.parseColor("#FF0000");
public ExtendedBackgoundColorSpan(int color) {
super(color);
}
public ExtendedBackgoundColorSpan(Parcel src) {
super(src);
}
/*Make text colour red*/
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(fgColor);
}
}
一切都很好,直到我复制/剪切然后粘贴跨区文本。然后它将失去其“红色”,但保留背景颜色。此外,粘贴的 Span 被识别为普通 BackgroundColorSpan
,而不是ExtendedBackgroundColorSpan
.
尝试覆盖 writeToParcel(Parcel dest, int flags)
来自基类,具有可设置(非最终)fgColor
,以及(也将其设置为构造函数),但没有任何效果。
当我尝试使用额外信息(如特殊标签或 ID)创建自定义范围时,我也遇到了这种行为。粘贴时,额外的信息,甚至跨度的扩展类型都会丢失。
我错过了什么?
编辑:这就是我所缺少的。以下内容来自Android开发者ClipData.Item
here :
Description of a single item in a ClipData.
The types than an individual item can currently contain are:
- Text: a basic string of text. This is actually a CharSequence, so it can be formatted text supported by corresponding Android built-in style spans. (Custom application spans are not supported and will be stripped when transporting through the clipboard.)
(强调我的。)
我将接受已接受的答案,因为这为我指明了正确的方向。
<rant>
(意思是看看我可能不能做什么,因为 Android 团队中的某个人决定我不应该做。我最终得到了一个自定义 EditText
,带有自定义粘贴逻辑,并且复制/剪切/粘贴操作的回调,只是为了实现一些本来应该是操作系统工作的东西。整个平台感觉就像一个巨大的黑客。) </rant>
最佳答案
你激励我享受 Spannables 带来的乐趣。没有机会扩展 BackgroundColorSpan
并实现自己的 ParcelableSpan
。框架不允许,请检查 ParcelableSpan reference 。否则,我尝试解决您的副本跨度问题,答案很简单:
SpannableString spannableString = new SpannableString(firstEditText.getText().toString());
spannableString.setSpan(new BackgroundColorSpan(Color.GREEN), 0, spannableString.length(), 0);
spannableString.setSpan(new ForegroundColorSpan(Color.RED), 0, spannableString.length(), 0);
字符串可以复制粘贴包含在设置范围之前,我已经检查过了。您可以将这两个跨度连接到一个类并将其与其他颜色一起使用。
关于Android 可跨度 : Copy/Cut custom Span in Edittext only Pastes the base class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51285321/