textView 添加超链接(两种实现方式)

时间:2021-08-12 12:58:27 

在textView添加超链接,有两种方式,第一种通过HTML格式化你的网址,一种是设置autolink,让系统自动识别超链接。

代码如下:

第一种


public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
TextView textView = new TextView(this);
String html = "有问题:\n";
html+="<a href='http://www.baidu.com'>百度一下</a>";//注意这里必须加上协议号,即http://。

//否则,系统会以为该链接是activity,而实际这个activity不存在,程序就崩溃。
CharSequence charSequence = Html.fromHtml(html);

textView.setText(charSequence);

textView.setMovementMethod(LinkMovementMethod.getInstance());
layout.addView(textView);
this.setContentView(layout,params);
}


第二种


public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
TextView textView = new TextView(this);
String html = "有问题:\n";
html+="www.baidu.com";//这里即使不加协议好HTTP;也能自动被系统识别出来。
textView.setText(html);
textView.setAutoLinkMask(Linkify.ALL);
textView.setMovementMethod(LinkMovementMethod.getInstance());
layout.addView(textView);
this.setContentView(layout,params);
}


总结一下就是,以html显示超链接,必须写全url。以setAutoLinkMask(Linkify.ALL)可以不用不用写全,就能自动识别出来。

这两种方法,都得设置一下setMovementMethod,才会跳转。
另外setAutoLinkMask不仅 识别超链接,包括电话号码之类的。

标签:textView,超链接
0
投稿

猜你喜欢

  • android 简单图片动画播放的实例代码

    2023-11-07 12:39:01
  • Java完美实现2048小游戏

    2023-06-14 12:59:25
  • JavaWeb实现多文件上传及zip打包下载

    2023-11-16 16:41:25
  • SpringBoot在IDEA中实现热部署的步骤

    2022-01-14 23:30:02
  • java8 Stream大数据量List分批处理切割方式

    2023-02-10 22:34:36
  • Spring Boot中@ConditionalOnProperty的使用方法

    2021-11-27 09:07:33
  • C#程序打成 一键安装包-InstallShield教程

    2022-11-19 06:02:07
  • c# 如何实现图片压缩

    2022-02-10 00:46:31
  • Spring源码解析之事务传播特性

    2021-08-14 16:49:39
  • C# using的本质及使用详解

    2022-10-10 06:11:23
  • C#实现微信跳一跳小游戏的自动跳跃助手开发实战

    2022-12-11 02:49:08
  • C# 绘制统计图大全(柱状图, 折线图, 扇形图)

    2023-03-12 09:16:26
  • Struts和servlet不能共存问题解决方法

    2022-09-20 07:26:59
  • C#使用Monitor类实现线程同步

    2021-07-20 03:01:14
  • 使用controller传boolean形式值

    2023-11-28 23:05:33
  • Java中Controller、Service、Dao/Mapper层的区别与用法

    2022-09-12 15:14:03
  • Intellij搭建springmvc常见问题解决方案

    2023-07-23 12:53:29
  • Springboot如何根据实体类生成数据库表

    2023-11-20 13:54:39
  • java简单坦克大战制作代码

    2023-02-07 05:08:37
  • SpringBoot接口如何统一异常处理

    2023-08-10 15:06:20
  • asp之家 软件编程 m.aspxhome.com