我有一些文本链接在一个TextView。现在我想让浏览器在用户点击链接时打开链接。我的TextView看起来像这样:
<string name="Info">Go to <a href="www.google.com">Google</a></string>
<TextView
android:id="@+id/Info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/OptionMarginBottom"
android:autoLink="web"
android:linksClickable="true"
android:text="@string/Info" />
链接显示正确的蓝色,但我不能点击它。为什么呢?
使用此方法
public static void addLink(TextView textView, String patternToMatch,
final String link) {
Linkify.TransformFilter filter = new Linkify.TransformFilter() {
@Override public String transformUrl(Matcher match, String url) {
return link;
}
};
Linkify.addLinks(textView, Pattern.compile(patternToMatch), null, null,
filter);
}
并用作
addLink(text, "^Android", "http://abhiandroidinfo.blogspot.in");
在TextView
上使用Linkify
Linkify.addLinks(yourTextviewObject, Linkify.WEB_URLS);
Linkify取一段文本和一个正则表达式,并把所有的正则表达式在文本中匹配为可点击的链接。
辅助方法:
public static void addLinks(TextView textView, String linkThis, String toThis) {
Pattern pattern = Pattern.compile(linkThis);
String scheme = toThis;
android.text.util.Linkify.addLinks(textView, pattern, scheme, new MatchFilter() {
@Override
public boolean acceptMatch(CharSequence s, int start, int end) {
return true;
}
}, new TransformFilter() {
@Override
public String transformUrl(Matcher match, String url) {
return "";
}
});
}
现在使用like:
String weblink = "WebsiteName";
String url = course.getString(TAG_Info);
TextView txtInfo= (TextView) findViewById(R.id.Info);
txtInfo.setText(userCanSeeThis);
addLinks(txtInfo, weblink, url);
更简单的方法是创建一个字符串并添加链接文本并在xml文件中,使textView:
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web"
android:text="@string/string_with_link" />