我对android,Java和sqlite都很陌生。对于我的第一个程序,我创建了一个程序,该程序将接受用户输入并放置在预定义文本中。
示例:" text" string1"更多文字" string2"更多文字"等
我的文字将是一种颜色,字符串将以另一种颜色显示。
我使用sqlite来分离我的数据和代码,这就是我碰壁的地方。试图找到有关如何将上述文本合并到数据库表中的一行/列的帮助。
只使用上面的一个示例我可以启动并运行。但是,上述示例将有50多个用于发布数据库,尤其是当我想在发布后添加更多数据库时。
答案 0 :(得分:6)
很可能你已经阅读了SpannableStringBuilder
,它允许你在TextView的内容中为文本添加颜色。看看下面的代码:
SpannableStringBuilder ssb = new SpannableStringBuilder(<your text>);
ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(255, 0, 0));
ssb.setSpan(fcs, 0, ssb.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(ssb);
上面的代码在大多数情况下都适用,但是你想要的是在单个TextView上使用不同的交替颜色。然后你应该做以下事情:
String text = your_text + text_from_database;
SpannableStringBuilder ssb = new SpannableStringBuilder(text);
ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(255, 0, 0));
ForegroundColorSpan fcs2 = new ForegroundColorSpan(Color.rgb(0, 255 0));
ssb.setSpan(fcs, 0, your_text, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.setSpan(fcs2, your_text.length(), ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(ssb);
上面的代码现在可以使用了,但是您会注意到,如果您添加了另一个文本your_another_text
并希望再次使用之前的fcs
实例,那么之前的颜色为{{1}现在将丢失其格式(颜色)。这次你需要创建另一个ForegroundColorSpan fcs3来格式化SpannableStringBuilder的第三部分。这里的关键是只在your_text
方法中使用一次字符样式。见下文:
setSpan
如果您知道SpannableStringBuilder中有固定数量的String元素,则此方法很好。如果您希望拥有动态长度和元素数量的TextView,则需要以不同的方法执行此操作。对我有用的是将每个字符串元素转换为SpannableString,使用String testTest = "abcdefgh";
String testTest2 = "ijklmnop";
String testTest3 = "qrstuvwxyz";
SpannableStringBuilder ssb = new SpannableStringBuilder(testTest+testTest2+testTest3);
ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(255, 0, 0));
ForegroundColorSpan fcs2 = new ForegroundColorSpan(Color.rgb(0, 255, 0));
ForegroundColorSpan fcs3 = new ForegroundColorSpan(Color.rgb(255, 0, 0));
ssb.setSpan(fcs, 0, testTest.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
ssb.setSpan(fcs2, testTest.length(), (testTest+testTest2).length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
ssb.setSpan(fcs3, (testTest+testTest2).length(), ssb.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
test.setText(ssb);
和setSpan
将其转换为TextView。如果您使用循环来构建TextView,这将非常有用。
append