效果
第一步:按如下所示代码创建一个用来高亮显示文本的工具类:
public class KeywordUtil {public static SpannableString highLight(int color, String text, String keyword) {SpannableString res = new SpannableString("\t\t\t" + text);Pattern pattern = Pattern.compile(keyword);Matcher matcher = pattern.matcher(res);while (matcher.find()) {int start = matcher.start();int end = matcher.end();res.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);}return res;}public static SpannableString highLight(int color,String text,String... keyword) {SpannableString res = new SpannableString("\t\t\t" + text);for (String key : keyword) {Pattern pattern = Pattern.compile(key);Matcher matcher = pattern.matcher(res);while (matcher.find()) {int start = matcher.start();int end = matcher.end();res.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);}}return res;}public static SpannableString highLight(int[] cs,String text,String... keyword) {SpannableString res = new SpannableString("\t\t\t" + text);for (int i = 0; i < color.length; i++) {Pattern pattern = Pattern.compile(keyword[i]);Matcher matcher = pattern.matcher(res);while (matcher.find()) {int start = matcher.start();int end = matcher.end();res.setSpan(new ForegroundColorSpan(cs[i]), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);}}return res;}
}
第二步:在主布局文件中添加三个id值分别为textView1、textView3、textView3的TextView控件,然后修改MainActivity类的代码如下所示:
public class MainActivity extends AppCompatActivity {private android.widget.TextView textView1;private android.widget.TextView textView2;private android.widget.TextView textView3;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);this.textView2 = (TextView) findViewById(R.id.textView2);this.textView1 = (TextView) findViewById(R.id.textView1);this.textView3 = (TextView) findViewById(R.id.textView3);String text = "随着棉花糖的出现,一种新……度,探讨处理权限请求的方法";SpannableString spanStr1 = KeywordUtil.highLight(Color.RED, text, "权限");textView1.setText(spanStr1);SpannableString spanStr2 = KeywordUtil.highLight(Color.RED, text, "棉花糖","权限","安卓");textView2.setText(spanStr2);SpannableString spanStr3 = KeywordUtil.highLight(new int[]{Color.RED,Color.GREEN,Color.BLUE}, text, "棉花糖","权限","安卓");textView3.setText(spanStr3);}
}