0

Im trying to add multiple html foreground formattings of a snackbar text programmatically.

In my strings.xml:

<string name="html_test">The html entries %1$s and %2$s are looking different.</string>

How i try to format them:

  public static Spanned getString(Context p_Context, int p_iResID, int p_iColor, String... p_Items) {
    int l_iColor = ContextCompat.getColor(p_Context, p_iColor);
    String l_HexColor = Integer.toHexString(l_iColor);

    String l_Before = "&lt;font color=" + l_HexColor + ">";
    String l_After = "&lt;/font>";

    Object[] l_Items = new String[p_Items.length];
    for(int i = 0; i < p_Items.length; i++) {
      l_Items[i] = l_Before + p_Items[i] + l_After;
    }

    return Html.fromHtml(p_Context.getString(p_iResID, l_Items));
  }

How i call the function:

getString(getContext(), R.string.html_test, R.color.blue, "Test1", "Test2");

Then i create a snackbar and pass the html formated text.

Snackbar l_SnackBar = Snackbar.make(p_Root, p_Text, p_iSnackBarLenght);
l_SnackBar.getView().setBackgroundColor(p_iBGColor);
return l_SnackBar;

The problem is that there is no html formatting of the two entries i passed into getString().

I don't want to use ![CDATA... because i read that there are some problems with the formatting.

beeb
  • 1,615
  • 1
  • 12
  • 24

1 Answers1

0

I didn't found a solution to format the foreground parameters of getString() with html. Now im doing it with SpannableString which works for me. My code looks like this now:

  public static SpannableString getString(Context p_Context, int p_iResID, int p_iColor, Object... p_Items) {
    String l_Feedback = p_Context.getString(p_iResID, p_Items);
    SpannableString l_SpannableFeedback = new SpannableString(l_Feedback);
    int l_iItemColor = ContextCompat.getColor(p_Context, p_iColor);

    for(Object l_Object : p_Items) {
      String l_Item = (String) l_Object;
      int l_iStartIndex = l_Feedback.indexOf(l_Item);
      int l_iEndIndex = l_iStartIndex + l_Item.length();

      l_SpannableFeedback.setSpan(new ForegroundColorSpan(l_iItemColor), l_iStartIndex, l_iEndIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
      l_SpannableFeedback.setSpan(new StyleSpan(Typeface.BOLD), l_iStartIndex, l_iEndIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    return l_SpannableFeedback;
  }
beeb
  • 1,615
  • 1
  • 12
  • 24