android || java 截取解析String特殊部分高亮
2020-05-13 本文已影响0人
倔强的小鹿
定义了这样的一坨文字,凡是用标签裱起来,都要
1.解析截取,
2.去标签,
3.包裹内容高亮显示
本周消费<colortag>128.31</colortag>元,余额<colortag>39.92</colortag>元
单纯的我想着自己写,于是****错误的示范****:
private CharSequence getMessage2(String str){
Map<Integer,Integer> indexMap = new LinkedHashMap<>();
String regex="<colortag>(.*?)</colortag>";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while (m.find()){
String x = m.group();
int index = str.indexOf(x);
String xx = x;
x = x.replace("<colortag>","");
x = x.replace("</colortag>","");
indexMap.put(index,x.length());
str = str.replace(xx,x);
}
return highLightKeyWords(str,indexMap);
}
private CharSequence highLightKeyWords(String text, Map<Integer,Integer> indexMap){
SpannableStringBuilder builder = new SpannableStringBuilder(text);
for(Map.Entry<Integer, Integer> entry : indexMap.entrySet()){
int mapKey = entry.getKey();
int mapValue = entry.getValue();
builder.setSpan(new ForegroundColorSpan(BaseUtils.getColor(R.color.base_fun_red_nor)), mapKey, mapKey + mapValue, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return builder;
}
后来我写着写着又想起了 Html.from
于是改成下面的样子:
private CharSequence getMessage(String str){
if (str.contains("<colortag>") && str.contains("</colortag>")){
str = str.replace("<colortag>","<font color=\"#FF0000\">");
str = str.replace("</colortag>","</font>");
return Html.fromHtml(str);
}
return str;
}
can call me ©Copyright
wangchenit@gmail.com