我有textview,我需要链接.这就是我在做什么..
TextView text = (TextView) view.findViewById(R.id.name);
text.setText("Android...Update from Android");
Pattern pattern = Pattern.compile("Android");
String scheme = "www.android.com";
Linkify.addLinks(text, pattern, scheme);
Run Code Online (Sandbox Code Playgroud)
文本视图正确显示文本"Android ...从Android更新",但我面临两个问题.
1)我的文本字符串有两个字符串"Android"的实例.所以,这两个文本都是链接的.我只希望第一次出现链接.我该怎么办呢?
2)当我单击linkfy文本时,它会打开浏览器,但URL很奇怪.它试图打开的网址是"www.comandroid".我不知道这里出了什么问题.URL中的文本"android"正在被替换.在链接文本时我做错了什么.
任何帮助将受到高度赞赏.
Fer*_* JS 22
简单的方法是将autoLink置于XML布局中.
android:autoLink="web"
Run Code Online (Sandbox Code Playgroud)
Sha*_*zon 19
我创建了一个简单的静态方法:
/**
* Add a link to the TextView which is given.
*
* @param textView the field containing the text
* @param patternToMatch a regex pattern to put a link around
* @param link the link to add
*/
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);
}
Run Code Online (Sandbox Code Playgroud)
OP可以简单地使用它:
addLink(text, "^Android", "http://www.android.com");
Run Code Online (Sandbox Code Playgroud)
我对Linkify没有多少经验.到目前为止,我想要做的就是将文本中的URL设置为链接,这些链接由不同版本的自动处理addLinks
.
但是,您在"Android"上匹配的正则表达式可以更改为仅匹配通过调整正则表达式启动字符串的正则表达式:
Pattern pattern = Pattern.compile("^Android");
Run Code Online (Sandbox Code Playgroud)
注意添加'^'.这告诉正则表达式匹配器在启动字符串时仅匹配模式"Android".如果这对你的琴弦有效,那就太好了.如果您有其他情况,您要链接的单词不在行的开头,则需要更多地探索正则表达式.我建议这个网站了解更多regular-expressions.info
如果你想打开文本中包含的所有网址,那么你可以这样做..
TextView textview=(TextView)findViewById(R.id.text);
textview.setText("Android....Update from android...www.android.com");
Linkify.addLinks(textview, Linkify.WEB_URLS);
textview.setMovementMethod(LinkMovementMethod.getInstance());
Run Code Online (Sandbox Code Playgroud)
它可能适用于所有网址.
从 Shawns 的回答和 SpunkerBaba 的评论中,我推出了这个助手类。这阻止了将您正在更改的内容添加到您的 url 的双重附加问题。
package com.your.package;
public class Linkify {
/**
* @param textView
* textView who's text you want to change
* @param linkThis
* a regex of what text to turn into a link
* @param toThis
* the url you want to send them to
*/
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 "";
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
用途:
Linkify.addLinks(profileTextView, "BlundellApps.com", "http://www.BlundellApps.com");
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
30495 次 |
最近记录: |