【问题标题】:Android: TextView with url end with -/\n Linkify wronglyAndroid:带有 url 的 TextView 以 -/\n Linkify 错误结尾
【发布时间】:2016-01-02 06:12:51
【问题描述】:

目前,我有一个类似

的字符串

http://www.example.com/defg-/\n字母


我将此字符串放入 TextView,并通过 setAutoLinkMask(Linkify.WEB_URLS) 和 setMovementMethod(LinkMovementMethod.getInstance())

使 url 可点击

但是,链接被错误识别,只有

http://www.example.com/defg   

突出显示但不突出

http://www.example.com/defg-/  

,并导致错误的 url。

我应该怎么做才能正确识别url?


示例结果(第二个链接被错误识别)

代码实现

    txtNorm = (TextView) findViewById(R.id.txtNorm);
    txtNorm.setText("http://www.example.com/defg-/");
    txtNorm.setAutoLinkMask(Linkify.WEB_URLS);
    txtNorm.setMovementMethod(LinkMovementMethod.getInstance());

    txtCustom = (TextView) findViewById(R.id.txtCustom);
    txtCustom.setText("http://www.example.com/defg-/\nletters");
    txtCustom.setAutoLinkMask(Linkify.WEB_URLS);
    txtCustom.setMovementMethod(LinkMovementMethod.getInstance());

【问题讨论】:

    标签: java android textview pattern-matching linkify


    【解决方案1】:

    我找到了一种可以尝试的方法。首先,您需要知道,如果您在 url 末尾添加 -/,这不是标准 Web Url 的常见格式。所以我做了一个自定义模式..

    String urlRegex="[://.a-zA-Z_-]+-/"; // carefully set your pattern.
            Pattern pattern = Pattern.compile(urlRegex);
            String url1="press http://www.example.com/defg-/\\ or on Android& to search it on google";
            text.setText(url1);
    
            Matcher matcher1=Pattern.compile(urlRegex).matcher(url1);
    
            while (matcher1.find()) {
    
                final String tag = matcher1.group(0);
    
                Linkify.addLinks(text, pattern, tag);
            }
    
            text.setMovementMethod(LinkMovementMethod.getInstance());
    

    【讨论】:

    • 抱歉,您如何提取正确的链接?我的问题正是询问如何提取 larfe 文本的链接。
    • 感谢您的回答,也许我会使用 code.tutsplus.com/tutorials/8-regular-expressions-you-should-know--net-6149 中提供的 URL 模式
    猜你喜欢
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多