Android中Textview超链接实现方式

2019-12-10 19:09:36王旭
TextView中的超链接可以通过几种方式实现:1.Html.fromHtml,2.Spannable,3.Linkify.addLinks。下面分别进行测试,包括修改字体样式,下划线样式,点击事件等,需要的朋友可以参考下  

TextView中的超链接可以通过几种方式实现:
一、Html.fromHtml方式

TextView,本身就支持部分的Html格式标签。这其中包括常用的字体大小颜色设置,文本链接等。使用起来也比较方便,只需要使用Html类转换一下即可: textView.setText(Html.fromHtml(str));

代码如下:

 public class Test10Activity extends Activity {
  TextView textView ;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_test10);
   textView = (TextView) findViewById(R.id.text);
   String webLinkText = "<a href='https://www.easck.com/pre>
	
	

这时候点击超链接并没有跳转效果,需要加上

textView.setMovementMethod(LinkMovementMethod.getInstance());
之后才会跳转。 这样点击之后会用默认浏览器打开url。

现在字体颜色和下划线是默认样式,修改字体颜色比较简单,可以直接用标签:

 String webLinkText =
   "<font color='#333333'><a href='https://www.easck.com/>  

二、Spannable方式

在xml中设置了android:autoLink="email|phone|web"后,url文字下面会有一条下划线,我们可以看URLSpan所继承的类ClickableSpan 类的源码,如下:

public abstract class ClickableSpan extends CharacterStyle implements UpdateAppearance {

   /
   * Performs the click action associated with this span.
   */

   public abstract void onClick(View widget);

   /
   * Makes the text underlined and in the link color.
   */

   @Override

   public void updateDrawState(TextPaint ds) {

    ds.setColor(ds.linkColor);

    ds.setUnderlineText(true);

   }

  }