【问题标题】:Is it possible to add 2 colors on a single Android Spannable?是否可以在单个 Android Spannable 上添加 2 种颜色?
【发布时间】:2020-12-09 13:31:33
【问题描述】:

我做拼写检查,想用红色显示所有错误的字母。

就像用户输入 Mossosoppo 并且正确的单词是密西西比一样。我想用红色显示错误的字母。

我尝试使用 SpannedString、SpannableString 和 SpannableStringBuilder。我还检查了 Google 会找到的所有示例。没有任何效果(= 最多 1 个字母显示为红色或位置后的所有字母)。

我尝试了所有可能的标志组合 - SPAN_INCLUSIVE_INCLUSIVE、INCLUSIVE_EXCLUSIVE、EXCLUSIVE_INCLUSIVE、EXCLUSIVE_EXCLUSIVE。

这也不允许在两个地方使用相同的颜色。 我能看到的最大值是颜色、粗体、斜体等不同属性的组合。

设置Span的接口是setSpan(Object _what_, int _start_, int _end_, int _flags_).

现在这并不能说明是否可以为同一属性(颜色)多次调用它。有人成功为单个字符串添加超过 1 个颜色跨度吗?

如果是这样我可以再次挖掘,也许我在测试所有可能的标志组合时出错了。目前我正在将代码切换到具有许多 TextViews 的 LinearLayout,其中每个 TextView 包含一个字符。那应该行得通。但它并不优雅。

【问题讨论】:

标签: android text spannable


【解决方案1】:

好的,感谢 Sajjad,我找到了解决方案。 可以添加 2 种颜色或更多颜色。但是 ForegroundColorSpan 只能使用一次。所以要设置红色 2 次,你需要 2 ForegroundColorSpan。如果您重复使用相同的 ForegroundColorSpan,它将不起作用。

        SpannableStringBuilder fullstring =  new SpannableStringBuilder();

        ForegroundColorSpan fg_red = new ForegroundColorSpan(Color.RED);
        ForegroundColorSpan fg_black = new ForegroundColorSpan(Color.BLACK);
        ForegroundColorSpan fg_red2 = new ForegroundColorSpan(Color.RED);
        ForegroundColorSpan fg_black2 = new ForegroundColorSpan(Color.BLACK);


        SpannableString blackText = new SpannableString("This is black");
        blackText.setSpan(fg_black, 0, blackText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        fullstring.append (blackText);

        SpannableString redText = new SpannableString("red");
        redText.setSpan(fg_red, 0, redText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        fullstring.append(redText);

        SpannableString blackText2 = new SpannableString("blackagain");
        blackText2.setSpan(fg_black2, 0, blackText2.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        fullstring.append(blackText2);

        SpannableString redText2 = new SpannableString("redagain");
        redText2.setSpan(fg_red2, 0, redText2.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        fullstring.append(redText2);

        return fullstring;

// the returned string can then be used for TextView.setText(); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 2018-06-12
    • 1970-01-01
    相关资源
    最近更新 更多