您的位置:首页 > 其它

TextView 中添加超链接

2016-01-26 14:43 363 查看
在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+="百度一下";//注意这里必须加上协议号,即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不仅 识别超链接,包括电话号码之类的。

详细出处参考:http://www.jb51.net/article/38160.htm

第三种
同一个TextView控件中有多处需要点击,并且点击后跳转到不同的位置
1、
SpannableString spanableInfo = new SpannableString(
"点击确认即表示您同意并签署《管理服务协议》及《风险提示书》");
int firsStar = spanableInfo.toString().indexOf("《");
int firstEnd = spanableInfo.toString().indexOf("》");
int end = spanableInfo.length();
// 1-管理服务协议页面; 2-金风险提示书页面
spanableInfo.setSpan(new Clickable( 1), firsStar, firstEnd,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spanableInfo.setSpan(new Clickable(2), firstEnd + 2, end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tvZybInputDesc.setText(spanableInfo);
//setMovementMethod()该方法必须调用,否则点击事件不响应
tvZybInputDesc.setMovementMethod(LinkMovementMethod.getInstance());

2、
class Clickable extends ClickableSpan {
// 1-跳转到投资咨询及管理服务协议页面; 2-挑战到投资资金风险提示书页面
private int type;
public Clickable(int type) {
super();
this.type = type;
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(getResources().getColor(R.color.text_gray_color));
ds.setUnderlineText(false);
}
@Override
public void onClick(View v) {
String userId = ConfigTools.getConfigValue(Constants.USER_ID, "");
String token = PageUtils.getTokenUtf8();
Intent sIntent = new Intent(ZybInputActivity.this, SszWebviewActivity.class);
if (type == 1) {
//处理管理服务协议的点击事件
} else {
// 处理风险提示书的点击事件
}
startActivity(sIntent);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: