S
S
Sergey Shilovsky2021-07-23 00:09:38
Android
Sergey Shilovsky, 2021-07-23 00:09:38

What's the best way to fit different styles on one line?

Good day. I often face the task when it is necessary to create a complex string: support for different styles, colors, sizes, etc., all this with support for arguments and in one TextView.

Task example: color the word UNKNOWN in the string UPDATE UNKNOWN TO %1$s in a different color.
I have identified 3 best ways to do this:

//#1
//<string name="update_unknown">UPDATE UNKNOWN TO %1$s</string>
//<string name="selected">UPDATE UNKNOWN TO %1$s</string>

val span = SpannableString(getString(R.string.update_unknown, arg))
val selected = getString(R.string.selected)
val start = span.indexOf(selected)
span.setSpan(
  ForegroundColorSpan(requireContext().getColor(R.color.selectedColor)),
  start,
  start + selected.length,
  Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
textView.text = span

//-------------------------------------------------------------------

//#2 Самый короткий, но нельзя вынести цвет в ресурсы.
//<string name="update_unknown_to_s"><![CDATA[UPDATE <font color="#6AE8EF">UNKNOWN</font> TO %1$s]]></string>

val text = getString(R.string.update_unknown_to_s, arg)
textView.text = HtmlCompat.fromHtml(text, HtmlCompat.FROM_HTML_MODE_COMPACT)

//-------------------------------------------------------------------

//#3
//<string name="update">UPDATE UNKNOWN TO %1$s</string>
//<string name="unknown">UNKNOWN</string>
//<string name="to_s">TO %1$s</string>

textView.text = buildSpannedString {
  append("${getString(R.string.update)} ")
  color(getColor(R.color.selectedColor)) {
    append("${getString(R.string.unknown)} ")
  }
  append("${getString(R.string.to_s, arg)} ")
}

Are there better ways and which one would you choose?

String resources are a requirement for localization support.
So far I have settled on the second option.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
rPman, 2021-07-23
@rPman

The spinnedString option is preferable, it is more concise, there are fewer places for errors, but it is verbose, on the other hand, in the code you will not only add string constants, you need coloring from logic, which means verbosity is no longer a problem.
The variant with html, as far as I understand, is more universal, it can be used with a template engine, i.e. when you already have message templates and they need to be brought to the final form, and collecting the final text, marking it with spinnedString, can be inconvenient.
So choose according to your needs.

M
Maxim Siomin, 2021-07-23
@MaxSiominDev

Well, you have to choose from the second or the first, the third one is not very good at all. Well, the second and first are both normal

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question