Reputation: 2995
I have a textview that should be in all caps and mark any urls found in it with a specific color, so naturaly I've tried textColorLink, with the option textAllCaps="true", however the url is not colored, my guess is that the regex does not match uppercase urls, since the url is colored if the same text is in lowercase.
I've tried solving it with this:
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);
Apparently it finds the text, however once again it is not colored. I've been at this for hours, how do you solve this?
Upvotes: 3
Views: 793
Reputation: 312
when you try to upperCase the string lose the color but if you add another SpannableString and pass to this the string.toUpperCase than you can setSpan...
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);
Should works...
Remove from xml the textAllCaps="true"
Upvotes: 2