gpt4 book ai didi

android - 在 textAllCaps 上设置 textColorLink?

转载 作者:太空狗 更新时间:2023-10-29 13:20:10 25 4
gpt4 key购买 nike

我有一个 textview,它应该全部大写,并用特定颜色标记其中找到的任何 url,所以自然地我尝试了 textColorLink,选项 textAllCaps="true ",但是 url 没有颜色,我的猜测是正则表达式不匹配大写的 url,因为如果相同的文本是小写的,则 url 是彩色的。

我试过用这个解决它:

Spannable formatted = new SpannableString(text);
Pattern url = Pattern.compile(
"(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]");
Matcher matcher = url.matcher(text.toLowerCase());

while (matcher.find())
{
Log.e("TEST",matcher.group());
int begIndex = matcher.start();
int endIdx = begIndex + matcher.group().length() - 1;
Log.e("Found", String.valueOf(begIndex));
formatted.setSpan(new ForegroundColorSpan(
getResources().getColor(android.R.color.holo_red_light)),
begIndex, endIdx, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
mTextView.setText(formatted);

显然它找到了文本,但是它又一次没有着色。我已经解决这个问题好几个小时了,你是如何解决这个问题的?

最佳答案

当您尝试大写时,字符串会失去颜色,但如果您添加另一个 SpannableString 并将 string.toUpperCase 传递给它,那么您可以设置 Span...

SpannableString formatted = new SpannableString(urlString);
Pattern url = Pattern.compile("(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]");
Matcher matcher = url.matcher(urlString.toLowerCase());

//Here you save the string in upper case
SpannableString stringUpperCase = new SpannableString(formatted.toString().toUpperCase());

while (matcher.find()) {

int begIndex = matcher.start();
int endIdx = begIndex + matcher.group().length() - 1;
stringUpperCase.setSpan(new ForegroundColorSpan(R.color.Red),
0, formatted.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
TextView text = (TextView) findViewById(R.id.textView);
text.setText(string);

应该可以...


从 xml 中删除 textAllCaps="true"

关于android - 在 textAllCaps 上设置 textColorLink?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29937101/

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