Morozov
Morozov

Reputation: 5250

How to use styles for 2 spannable string?

I create a variable where add 2 lines using SpannableStringBuilder. After i use span for each of string. But unfortunately the style applied not correctly. Something wrong with my positions, i need to use red color only for item.statusDecription(ex: 26 Jun 2020, 12:54) What might be the problem?

val typeface = ResourcesCompat.getFont(listItemView.context, R.font.roboto_bold)
val consentDescription = SpannableStringBuilder(item.consentDescription)
val statusDescription = SpannableStringBuilder(item.statusDescription)
val spannable = SpannableStringBuilder("$consentDescription $statusDescription")
spannable.apply {
    setSpan(StyleSpan(typeface!!.style), 0, item.consentDescription.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    setSpan(
        ForegroundColorSpan(
            ContextCompat.getColor(
                listItemView.context,
                R.color.grey_100
            )
        ), 0, item.consentDescription.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE
    )
    setSpan(StyleSpan(typeface.style), item.statusDescription.indexOf(item.statusDescription, 0), item.statusDescription.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    setSpan(
        ForegroundColorSpan(
            ContextCompat.getColor(
                listItemView.context,
                R.color.red
            )
        ), item.statusDescription.indexOf(item.statusDescription, 0), item.statusDescription.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE
    )
}
subTitleView.text = spannable

enter image description here

Upvotes: 0

Views: 39

Answers (1)

M D
M D

Reputation: 47807

Try this way

    val description ="Sprint Bank Example"
    val status ="5 26 Jun 2020, 12:54"
    val typeface = ResourcesCompat.getFont(this, R.font.calibri)

    val spannableDescription = SpannableString(description)
    val spannableStatus = SpannableString(status)

    val spannableBuilder = SpannableStringBuilder().apply {
        spannableDescription.setSpan(
            ForegroundColorSpan(context.getColorCompat(R.color.gray10)), 0, spannableDescription.length,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        spannableDescription.setSpan(typeface, 0, description.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

        append(spannableDescription)

        spannableStatus.setSpan(
            ForegroundColorSpan(context.getColorCompat(R.color.red)), 0, spannableStatus.length,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        spannableStatus.setSpan(typeface, 0, status.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

        append("\n")
        append(spannableStatus)
    }

    subTitleView.text  = spannableBuilder

Output:

enter image description here

Upvotes: 1

Related Questions