我有以下字符串形式的输入数据:"Hello #this# is #sample# text。“
它为#个字符之间的所有元素设置背景颜色。这是我到目前为止所得到的:
public static CharSequence colorBackground(CharSequence text) {
Pattern pattern = Pattern.compile("#(.*?)#");
Spannable spannable = new SpannableString( text );
if( pattern != null )
{
Matcher matcher = pattern.matcher( text );
while( matcher.find() )
{
int start = matcher.start();
int end = matcher.end();
CharacterStyle span = new BackgroundColorSpan(0xFF404040);
spannable.setSpan( span, start, end, 0 );
}
}
return spannable;
}设置背景颜色可以,但占位符#也会被设置为样式。如何在返回结果前删除它们,因为CharSequence不存在ReplaceAll方法?
我使用此函数在ListView中设置TextView行的样式。在添加这个样式函数后,在模拟器中感觉有点慢。也许我应该以其他方式来处理它,例如使用自定义TextView和自定义绘图函数?
发布于 2012-01-10 09:22:59
这听起来像是一件有趣的事情,试图弄清楚。
关键是SpannableStringBuilder。使用SpannableString时,文本本身是不可变的,但使用SpannableStringBuilder时,文本和标记都可以更改。考虑到这一点,我对您的代码片段进行了一些修改,以满足您的需要:
public static CharSequence colorBackground(CharSequence text) {
Pattern pattern = Pattern.compile("#(.*?)#");
SpannableStringBuilder ssb = new SpannableStringBuilder( text );
if( pattern != null )
{
Matcher matcher = pattern.matcher( text );
int matchesSoFar = 0;
while( matcher.find() )
{
int start = matcher.start() - (matchesSoFar * 2);
int end = matcher.end() - (matchesSoFar * 2);
CharacterStyle span = new BackgroundColorSpan(0xFF404040);
ssb.setSpan( span, start + 1, end - 1, 0 );
ssb.delete(start, start + 1);
ssb.delete(end - 2, end -1);
matchesSoFar++;
}
}
return ssb;
}一般来说,我对Spannables没有太多的经验,我不知道我删除"#“的方式是否是最好的方法,但它似乎有效。
发布于 2012-01-10 08:52:19
如何在返回结果前删除它们,因为CharSequence不存在ReplaceAll方法?
您可以采用Html.fromHtml()的方法--构建SpannedString,不要尝试在适当的地方修改它。
https://stackoverflow.com/questions/8796486
复制相似问题