Android 可跨度 : Copy/Cut custom Span in Edittext only Pastes the base class

标签 android android-edittext spannable text-styling

我正在尝试扩展一些跨度,以便它们可能成为复合的(以避免必须在一段文本上设置多个跨度),和/或存储有关它们自身的更多信息(例如“类型”和“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/

相关文章:

android - EditText 上的 ImageSpan(笑脸)。使用 SwiftKey 键盘不起作用

android - 在 span 中隐藏字符串内容

java - 将 Parcelable 对象传递给新 Activity 返回 null

android - Google Play控制台仅在某些LG型号上报告了InflateException,而没有更多详细信息:如何更深入?

Android:如何在聚焦时将 ScrollView 中的 EditText 放在另一个 View 上方?

android - EditText 空格字符换行?

android - 编辑文本 : Differentiate between text change by setText() or by keyboard input

java - 如何模拟AppCompatActivity和ListActivity扩展行为

java - Android下HttpURLConnection的默认超时时间是多少?

android - 在 TextView 中使用 SpannableStringBuilder 的段落间距