繁体   English   中英

单击TextView中的链接

[英]Click on Link in TextView

我在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 "";
            }
        });
    }

现在使用如下所示:

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" />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM