Search code examples
androidstringtextviewspannablestring

Style text of parameter in getString(int resId, Object... formatArgs) method


I have two String resources as such:

<string name="give_us_feedback">Give us feedback at %1$s if you want to make the app even better!</string>  
<string name="email">[email protected]</string>

I'd like to style the email part to be blue and underlined to indicate that the user can click on it (the whole TextView, not just the email text). I know to use SpannableString to color text, but it doesn't seem to work when I'm combining two strings via getString(int resId, Object... formatArgs), presumably because getString() will perform a cast or a .toString() on the Object being sent. Here's what doesn't work:

TextView emailTV = new TextView(this);
SpannableString email = new SpannableString(getString(R.string.email));
email.setSpan(new UnderlineSpan(), 0, email.length() - 1, 0);
email.setSpan(new ForegroundColorSpan(Color.BLUE), 0, email.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
String feedback = getString(R.string.give_us_feedback, email);
emailTV.setText(feedback);

Any ideas?


Solution

  • It's a bit tricky. Converting back to charsequence (String feedback = getString(R.string.give_us_feedback, email);) makes disappear the Spannable. Try this way (you want to check for the correct indexes in your string)

    String emailString = getString(R.string.email);
    String feedback = getString(R.string.give_us_feedback, emailString);
    SpannableString email = new SpannableString(feedback);
    int startIndex = feedBack.indexOf(emailString);
    int endIndex = startIndex + emailString.length();
    email.setSpan(new UnderlineSpan(), startIndex, endIndex, 0);
    email.setSpan(new ForegroundColorSpan(Color.BLUE), startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    emailTV.setText(email);