aik*_*rei 3 android textview spannablestring
我正在努力制作一款游戏来帮助孩子们学习数学.我为代码编号,以便他们可以遵循逻辑.我还使用textView.append()来构建一个长字符串以放入活动中.
因为我在指令中重复使用相同的数字/符号,我想要一种方法来轻松回收SpannableStrings,但似乎我所做的更改在第一次正确应用,但此后有时工作,有时部分工作(例如正确的大小)/alignment,但颜色错误),或根本不工作.我正在混合这一切.我似乎无法在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);
Run Code Online (Sandbox Code Playgroud)
(请注意,我没有提供XX,YY或ZZ的代码......因为我必须从共享首选项设置中获取数据,所以它更复杂一些,但这些问题与其他数学符号的问题基本相同/运算符).
这是最终的屏幕截图:

也许我问题的最好例子是+(加号).首先,它是预期的黑色,但后来只有4个字符(包括空格),它是错误的颜色(蓝色,它可能来自前一个SpannableString),虽然对齐和大小正确.在下一个彩色字符串中,它按预期显示(黑色,居中,大),但之后在后续的"彩色"字符串(小,左对齐,绿色,如段落文本)中根本没有格式化.使用的代码与上面完全相同(即math1.append(PLUS);),但输出并不是我所期望的.
最后一条信息:在全局声明我的变量之前,我每次使用相同的makeBlack()和math1.append()函数在本地声明它们,并且它工作得很好.在全局设置我的变量后,我只会遇到这种奇怪的行为.
对这里出了什么问题的任何建议?
您不能多次重复使用相同的跨度.即使跨度完全相同,您也需要为要更改的字符串的每个部分创建唯一的跨度.
我不知道我在哪里读到这个,但我可以确认答案.
为您想要更改的每件事创建一个独特的范围.
小智 5
可以多次使用相同的跨度
CharacterStyle.wrap(CharacterStyle c)
Run Code Online (Sandbox Code Playgroud)
每次需要使用相同的跨度时,将其作为参数。
| 归档时间: |
|
| 查看次数: |
3682 次 |
| 最近记录: |