Android学习—— TextView ClickableSpan 点击链接事件 改超链接颜色

来源:互联网 发布:linux 同步时区 编辑:程序博客网 时间:2024/06/01 21:06
private SpannableStringBuilder dealWeiboContent(String weiboContent,TextView textView) {Pattern pattern = Pattern.compile("((http://|https://){1}[\\w\\.\\-/:]+)|(#(.+?)#)|(@[\\u4e00-\\u9fa5\\w\\-]+)");temp = weiboContent;Matcher matcher = pattern.matcher(temp);List<String> list = new LinkedList<String>();while (matcher.find()) {if (!list.contains(matcher.group())) {temp = temp.replace(matcher.group(),"<a href=\"" + matcher.group() + "\">"+ matcher.group() + "</a>");/*temp = temp.replace(matcher.group(),"<font color='#365C7C'><a href='" + matcher.group() + "'>"+ matcher.group() + "</a></font>");*/}list.add(matcher.group());}textView.setText(Html.fromHtml(temp));System.out.println("temp" + temp);textView.setMovementMethod(LinkMovementMethod.getInstance());CharSequence text = textView.getText();if (text instanceof Spannable) {int end = text.length();Spannable sp = (Spannable) textView.getText();URLSpan[] urls = sp.getSpans(0, end, URLSpan.class);SpannableStringBuilder style = new SpannableStringBuilder(text);style.clearSpans();for (URLSpan url : urls) {style.setSpan(((ThinksnsWeiboContent) activityContent).typeClick(url.getURL()), sp.getSpanStart(url), sp.getSpanEnd(url), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);}return style;}return null;}


自定义方法

public ClickableSpan typeClick(final String value) {char type = value.charAt(0);switch (type) {case '@':return new ClickableSpan() {@Overridepublic void onClick(View widget) {// TODO Auto-generated method stubString uname = "";uname = value.substring(1, value.length());System.out.println("weiboContent---uanme---"+uname);}@Overridepublic void updateDrawState(TextPaint ds) { ds.setColor(Color.argb(255, 54, 92, 124));        ds.setUnderlineText(true);}};


下文转自:

转载注明本文地址: http://orgcent.com/android-textview-no-underline-hyperlink/

和HTML中的一样,默认超链接都带下划线的,下面的方案可以在TextView中去掉超链接的下划线:

1、重写ClickableSpan类来去掉下划线样式(系统默认使用ClickableSpan来封装超链接)

//无下划线超链接,使用textColorLink、textColorHighlight分别修改超链接前景色和按下时的颜色private class NoLineClickSpan extends ClickableSpan {String text;public NoLineClickSpan(String text) {    super();    this.text = text;}@Overridepublic void updateDrawState(TextPaint ds) {    ds.setColor(ds.linkColor);    ds.setUnderlineText(false); //去掉下划线}@Overridepublic void onClick(View widget) {    processHyperLinkClick(text); //点击超链接时调用}}


2、把超链接文本封装为NoLineClickSpan对象,并添加到TextView中

TextView tv = findViewById(R.id.tv_click);SpannableString spStr = new SpannableString("萝卜白菜博客-->http://orgcent.com");ClickSpan clickSpan = new NoLineClickSpan(vo); //设置超链接spStr.setSpan(clickSpan, 0, str.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);tv.append(spStr);tv.setMovementMethod(LinkMovementMethod.getInstance());

PS:不用把TextView的属性autoLink设为”all”.

3、设置超链接为可点击状态

tv.setMovementMethod(LinkMovementMethod.getInstance());

PS:在NoLineClickSpan类中实现onClick()回调方法.