android - SpannableString 第一次改变颜色,但在重复使用时不改变颜色

标签 android textview spannablestring

我正在尝试制作一款游戏来帮助 children 学习数学。我给代码编号上色,以便它们可以遵循逻辑。我还使用 textView.append() 构建一个长字符串以放入 Activity 中。

因为我在指令中重复使用相同的数字/符号,所以我想要一种轻松回收 SpannableString 的方法,但似乎我所做的更改第一次应用正确,但此后有时有效,有时部分有效(例如,尺寸/对齐正确,但颜色错误),或者根本不起作用。我混合了这一切。我似乎无法在 Stackoverflow 或 Google 的其他任何地方找到任何遇到类似问题的人。

这是我的代码(简化版):

    // Declare static variables
    public static Spannable PLUS = new SpannableString("+ ");
    public static Spannable MINUS = new SpannableString("- ");
    public static Spannable TIMES = new SpannableString("X ");
    public static Spannable DIVIDED_BY = new SpannableString("/ ");
    public static Spannable EQUALS = new SpannableString("= ");

    // Function to color these strings.
    public void colorStrings() {
    makeBlack(PLUS);
    makeBlack(MINUS);
    makeBlack(TIMES);
    makeBlack(DIVIDED_BY);
    makeBlack(EQUALS);
    makeBlack(QMARK);
    }

    // Function that actually sets color, size, and alignment.
    public Spannable makeBlack(Spannable s) {s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_black)), 0, s.length()-1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    s.setSpan(new AbsoluteSizeSpan((int) getResources().getDimension(R.dimen.big_text)), 0, s.length()-1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    s.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, s.length()-1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return s;
    }

    // Implementing above code by setting math1 TextView to give it colors.
    // Note that this is the exact code used for the first colored string in the
    // screen capture below.
    math1.setText(XX);
    math1.append(PLUS);
    math1.append(YY);
    math1.append(PLUS);
    math1.append(ZZ);
    math1.append(EQUALS);
    math1.append(QMARK);

(请注意,我没有提供 XX、YY 或 ZZ 的代码……它有点复杂,因为我必须从 sharedpreference 设置中获取数据,但这些遇到的问题与其他数学符号/运算符)。

这是生成的屏幕截图:

enter image description here

也许我的问题的最好例子是 +(加号)。 起初,它如预期的那样是黑色的,但仅在 4 个字符之后(包括空格)它的颜色是错误的(蓝色,很可能是从之前的 SpannableString 得到的),尽管对齐和大小正确。在下一个彩色字符串中,它按预期显示(黑色、居中、大),但之后它在随后的“彩色”字符串(小、左对齐、绿色,如段落文本)中根本没有格式化。 使用的代码看起来与上面完全一样(即 math1.append(PLUS);),但输出与我预期的不一致。

最后一条信息:在全局声明我的变量之前,我每次都使用相同的 makeBlack() 和 math1.append() 函数在本地声明它们,并且效果很好。在全局设置我的变量后,我才得到这种奇怪的行为。

对这里出了什么问题有什么建议吗?

最佳答案

您不能多次重复使用相同的跨度。即使跨度完全相同,您也需要为要更改的字符串的每个部分创建一个唯一的跨度。

我不确定我在哪里读到的,但我可以确认答案。

为您想要更改的每个内容创建一个唯一的跨度。

关于android - SpannableString 第一次改变颜色,但在重复使用时不改变颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20077457/

相关文章:

java - SharedPreferences 在不重新启动应用程序的情况下不保存

android - 将 TextView 添加到表面 View

java - 数组数组(二维数组)没有像我想要的那样在 TextView 中打印。

android - 收到 C2DM 推送通知时更改 Activity 行为

java - ListView 不会显示 - 空白屏幕

android - 在 android 中使用 Telephony Manager 查找 IMEI 号码

Swift change String with range & and shouldChangeTextInRange 如何知道退格

android - 如何在 staticlayout 和 surfaceview 中包含可点击的文本

android - 椭圆化 TextView 中 SpannableString 的各行

android - spannablestring 不适用于以编程方式创建的按钮