Android-TextView关键字高亮与超链接
目的:
将TextView里文本中的某些关键字高亮,并且设置超链接,可以进行页面的跳转
实现方法:
使用SpannableString,采用正则表达来搜索文本中的关键字;
设置关键字的超链接通过重写ClickableSpan来实现
1 // 加载文章内容高亮多个关键字,只高亮一个关键字去掉循环 2 String[] keywords = new String[] { "power", "internet" }; 3 SpannableString s = new SpannableString(getResources().getString( 4 R.string.papercontent)); 5 for (int i = 0; i < keywords.length; i++) { 6 Pattern p = Pattern.compile(keywords[i] + "\\W"); 7 Matcher m = p.matcher(s); 8 while (m.find()) { 9 int start = m.start(); 10 int end = m.end() - 1; 11 Intent intent = new Intent(getApplicationContext(), 12 KeyWord.class); 13 s.setSpan(new IntentSpan(intent), start, end, 14 Spannable.SPAN_EXCLUSIVE_INCLUSIVE); 15 } 16 } 17 tvContent.setText(s); 18 tvContent.setMovementMethod(LinkMovementMethod.getInstance());
1 /** 2 * 重写ClickableSpan中的onClick,实现点击效果 3 * @author zengjiyang 4 */ 5 public class IntentSpan extends ClickableSpan implements ParcelableSpan { 6 private Intent mIntent; 7 8 public IntentSpan(Intent mIntent) { 9 super(); 10 this.mIntent = mIntent; 11 } 12 13 @Override 14 public int describeContents() { 15 // TODO Auto-generated method stub 16 return 0; 17 } 18 19 @Override 20 public void writeToParcel(Parcel dest, int flags) { 21 // TODO Auto-generated method stub 22 } 23 24 @Override 25 public int getSpanTypeId() { 26 // TODO Auto-generated method stub 27 return 100; 28 } 29 30 @Override 31 public void onClick(View widget) { 32 // TODO Auto-generated method stub 33 Context context = widget.getContext(); 34 context.startActivity(mIntent); 35 } 36 37 @Override 38 public void updateDrawState(TextPaint ds) { 39 // TODO Auto-generated method stub 40 super.updateDrawState(ds); 41 ds.setColor(Color.RED); 42 ds.setUnderlineText(false); 43 ds.bgColor = Color.TRANSPARENT; 44 } 45 46 }
PS:目前就这些,日后想到再补充