在 textAllCaps 上设置 textColorLink?

Set textColorLink on textAllCaps?

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