gpt4 book ai didi

android - 我可以在使用 Linkify 后更改 TextView 链接文本吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:01:06 25 4
gpt4 key购买 nike

是否可以在使用 Linkify 创建链接后更改 TextView 文本?我有一些东西,我希望 url 有两个字段,一个名称和一个 id,但我只希望文本显示名称。

所以我从一个包含名称和 ID 的文本的 TextView 开始,然后链接化以创建与这两个字段的适当链接。但是为了显示,我不想显示id。

这可能吗?

最佳答案

这有点痛苦,但是是的。所以 Linkify 基本上做了一些事情。首先,它扫描 textview 的内容以查找与 url 相匹配的字符串。接下来它为匹配它的那些部分创建 UrlSpan 和 ForegroundColorSpan。然后它设置 TextView 的 MovementMethod。

这里的重要部分是 UrlSpan 的。如果您使用 TextView 并调用 getText(),请注意它返回一个 CharSequence。这很可能是某种跨越。您可以从 Spanned 中询问 getSpans(),特别是 UrlSpans。一旦您知道了所有这些跨度,您就可以遍历列表并查找旧跨度对象并将其替换为新跨度对象。

mTextView.setText(someString, TextView.BufferType.SPANNABLE);
if(Linkify.addLinks(mTextView, Linkify.ALL)) {
//You can use a SpannableStringBuilder here if you are going to
// manipulate the displayable text too. However if not this should be fine.
Spannable spannable = (Spannable) mTextView.getText();
// Now we go through all the urls that were setup and recreate them with
// with the custom data on the url.
URLSpan[] spans = spannable.getSpans(0, spannable.length, URLSpan.class);
for (URLSpan span : spans) {
// If you do manipulate the displayable text, like by removing the id
// from it or what not, be sure to keep track of the start and ends
// because they will obviously change.
// In which case you may have to update the ForegroundColorSpan's as well
// depending on the flags used
int start = spannable.getSpanStart(span);
int end = spannable.getSpanEnd(span);
int flags = spannable.getSpanFlags(span);
spannable.removeSpan(span);
// Create your new real url with the parameter you want on it.
URLSpan myUrlSpan = new URLSpan(Uri.parse(span.getUrl).addQueryParam("foo", "bar");
spannable.setSpan(myUrlSpan, start, end, flags);
}
mTextView.setText(spannable);
}

希望这是有道理的。 Linkify 只是一个设置正确 Span 的好工具。呈现文本时,跨度只会被解释。

关于android - 我可以在使用 Linkify 后更改 TextView 链接文本吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3983409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com