【问题标题】:Cannot insert custom links in TextView无法在 TextView 中插入自定义链接
【发布时间】:2012-01-09 02:13:02
【问题描述】:

我正在尝试插入指向 TextView 的链接,以使它们开始新的活动。我为我的Utils 类写了一个方法来做到这一点:

public static final String tagPattern = "#([^ ]+)";
public static final String tagReplace = "<a href=\"org.openihs.seendroid://display/tag/$1/\">#$1</a>";
public static final String userPattern = "@([^ ]+)";
public static final String userReplace = "<a href=\"org.openihs.seendroid://display/user/$1/\">@$1</a>";
static public void linkify(TextView view) {
    String text = view.getText().toString();
    text = text.replaceAll(Utils.tagPattern, Utils.tagReplace);
    text = text.replaceAll(Utils.userPattern, Utils.userReplace);
    view.setMovementMethod(LinkMovementMethod.getInstance());
    view.setText(Html.fromHtml(text));
    Log.d("SeenDroid", text);
    Linkify.addLinks(view, Linkify.ALL);
}

一个示例输出(到 logcat)是:

foo <a href="org.openihs.seendroid://display/tag/bar/">#bar</a> baz http://google.fr/

而真正的 UI 将 http://google.fr/ 作为链接提供(预期行为),但将 #bar 作为普通文本提供(意外行为)。

TextView 在 ListView 中。

有解决这个问题的想法吗?

问候, 程序验证

【问题讨论】:

    标签: android hyperlink textview linkify


    【解决方案1】:

    Linkify 的工作方式与您尝试使用它的方式略有不同。

    public static final String AUTHORITY = "your_package.your_content_provider";
    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/tag/");
    Pattern pattern = Pattern.compile(tagPattern);
    Linkify.addLinks(view, pattern, CONTENT_URI.toString());
    

    其中 CONTENT_URI 指的是您在清单中注册的 ContentProvider

    【讨论】:

      【解决方案2】:

      不要进行替换。 Html.fromHtml 已经正确处理了标签。

      【讨论】:

      • Html.fromHtml 如何知道我希望#tag 和@user 在用户点击它们时启动 SearchTagActivity 和 ShowUserActivity?
      • 哦,等等。我忘了提供模式。第一篇文章已编辑。
      猜你喜欢
      • 1970-01-01
      • 2018-02-11
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多