gpt4 book ai didi

android - 从 spannable CharSequence 中删除字符

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:01:26 25 4
gpt4 key购买 nike

我在字符串中有以下输入数据:“你好#this# 是#sample# 文本。”

它为 # 个字符之间的所有元素设置背景色。这是我到目前为止得到的:

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?

最佳答案

这听起来是一件有趣的事情。

关键是 SpannableStringBuilder .使用 SpannableString 时,文本本身是不可变的,但使用 SpannableStringBuilder 时,文本和标记都可以更改。考虑到这一点,我稍微修改了您的代码 fragment 以执行您想要的操作:

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 没有太多经验,我不知道我删除“#”的方法是否是最好的方法,但它似乎有效。

关于android - 从 spannable CharSequence 中删除字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8796486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com