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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2021-03-18 我要评论
想了解textView 添加超链接(两种实现方式)的相关内容吗,在本文为您仔细讲解textView 超链接的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:textView,超链接,下面大家一起来学习吧。
在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不仅 识别超链接,包括电话号码之类的。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们