现在的位置: 首页 > 综合 > 正文

Android学习札记45:在TextView中设置超链接

2017年12月17日 ⁄ 综合 ⁄ 共 1217字 ⁄ 字号 评论关闭


1、实现文本超链接

/**
* 设置超链接
* 在 layout /*.xml 中设置 TextView 属性 android:autoLink="all" 即可
* 支持:web/phone/email/map/all/none
*/
hyperlinkTextView = (TextView)findViewById(R.id.hyperlinkTextView);
hyperlinkTextView.setText("my blog -> http://orgcent.com");



2、实现无下划线超链接

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

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

// 无下划线超链接,使用 textColorLink、textColorHighlight 分别修改超链接前景色和按下时的颜色
private class NoLineClickSpan extends ClickableSpan {

	String text;

	public NoLineClickSpan(String text) {
		super();
		this.text = text;
	}

	@Override
	public void updateDrawState(TextPaint ds) {
		ds.setColor(ds.linkColor);
		ds.setUnderlineText(false);	// 去掉下划线
	}

	@Override
	public 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);

PS:不用把 TextView 的属性 autoLink 设置为"all"


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

tv.setMovementMethod(LinkMovementMethod.getInstance());



参考资料:

http://orgcent.com/android-textview-style-hyperlink/

http://orgcent.com/android-textview-no-underline-hyperlink/




抱歉!评论已关闭.