Android实现TextView字符串关键字变色的方法

一、字符串关键字变色

在界面显示的时候,偶尔需要将某些字符串中特定的字符串重点标出

如下图所示:

Android实现TextView字符串关键字变色的方法

便有了下面的方法。这个方法针对于比较 固定的字符串 ,并且需要自己 计算 需要变色的文字 位置 ,代码如下:

public static CharSequence setColor(Context context, String text, String text1, String text2) {
 SpannableStringBuilder style = new SpannableStringBuilder(text);
// 关键字“孤舟”变色,0-text1.length()
 style.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.colorPrimary)), 0, text1.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// 关键字“寒江雪”变色,text1.length() + 6-text1.length() + 6 + text2.length()
 style.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.colorAccent)), text1.length() + 6, text1.length() + 6 + text2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
 return style;
}

二、搜索关键字变色

要使搜索关键字变色,只需要对比关键字是否和字符串之间的某些字相同,然后将相同的字改变颜色就行了。

首先说一下 如何判断一个字符串包含另一个字符串 ,有两种方法:

1. string.indexOf("xxx"); ——这个方法用于查找关键字的位置,返回一个int值,没找到则返回-1;

2. string.contains("xxx"); ——这个方法是为了查看一个字符串中是否包含关键字,会返回一个boolean值。

下面这个方法用到的就是 indexOf() 。

Android实现TextView字符串关键字变色的方法
将关键字变色

代码如下:

public static CharSequence matcherSearchText(int color, String string, String keyWord) {
 SpannableStringBuilder builder = new SpannableStringBuilder(string);
 int indexOf = string.indexOf(keyWord);
 if (indexOf != -1) {
 builder.setSpan(new ForegroundColorSpan(color), indexOf, indexOf + keyWord.length(), SPAN_EXCLUSIVE_EXCLUSIVE);
 }
 return builder;
}

3.搜索关键字全部变色

上述方法很简单对不对?但是有一个很明显的问题,也在上图中标注出来了,就是不能使所有的关键字都变色,只能第一个变色。

下面这个方法就是要是所有的关键字都变色,就需要另外的方法了。

Android实现TextView字符串关键字变色的方法
所有关键字变色

代码如下:

public static SpannableString matcherSearchText(int color, String text, String keyword) {
 SpannableString ss = new SpannableString(text);
​
 Pattern pattern = Pattern.compile(keyword);
 Matcher matcher = pattern.matcher(ss);
​
 while (matcher.find()) {
 int start = matcher.start();
 int end = matcher.end();
 ss.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
 }
​
 return ss;
}

4.搜索关键字全部变色,且不区分大小写

上述方法依旧很简单对不对?那么问题又来了,上述方法虽然是把所有相同的字都标出来了,但如果是字母,肯定会遇到大小写的问题,而搜索不需要区分大小写。

首先也介绍两个String的方法: toUpperCase() toLowerCase() ,目的是为了将字符串中的字母统一成大写或者小写。(别的字符不会发生任何改变)

要达到目的就很简单了,只需要在比较的时候,先将字母大小写统一,就能得到想要的效果。比如搜'a',所有'a'和'A'都会变色了。

注1:只是在判断的时候统一大小写,在最终显示的时候还是要显示服务器给的字符串。

注2:用这个方法就不用正则啦,简单方便。(不想用正则,在网上找了好久都没有比较明确的答案,悲剧。)

Android实现TextView字符串关键字变色的方法
所有关键字变色,且不区分大小写

代码如下:

public static SpannableString matcherSearchTitle(int color, String text, String keyword) {
 String string = text.toLowerCase();
 String key = keyword.toLowerCase();
​
 Pattern pattern = Pattern.compile(key);
 Matcher matcher = pattern.matcher(string);
​
 SpannableString ss = new SpannableString(text);
 while (matcher.find()) {
 int start = matcher.start();
 int end = matcher.end();
 ss.setSpan(new ForegroundColorSpan(color), start, end,
     Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
 }
 return ss;
}

总结

以上就是我所总结的Android实现TextView字符串关键字变色的一些方法了,希望本文的内容对各位Android开发者们能有所帮助,如果有疑问大家可以留言交流。