Vladimir Fisher
Vladimir Fisher

Reputation: 2719

Android: How to combine text and icons in one TextView

Hi can I combine usual text with bold text and images like this, in any order? enter image description here

Thanks!

Upvotes: 3

Views: 751

Answers (1)

i30mb1
i30mb1

Reputation: 4786

One way to do this is to use SpannableStringBuilder. To add bold text you can do this :

        val text = SpannableStringBuilder()
            .append("В программе")
            .append(" ")
            .bold { append("Телефон") }

To add image you can use hand cook extension like this (i write it only for DrawableRes for you) :

    fun SpannableStringBuilder.drawable(
        tv: TextView,
        @DrawableRes drawable: Int,
    ): SpannableStringBuilder {
        val icon = ContextCompat.getDrawable(tv.context, drawable)!!
        icon.setBounds(0, 0, tv.lineHeight, tv.lineHeight)
        return inSpans(ImageSpan(icon, DynamicDrawableSpan.ALIGN_BOTTOM)) { append("$drawable") }
    }

So the final code for your first string with image will be look like this :

val text = SpannableStringBuilder()
    .append("В программе")
    .append(" ")
    .bold { append("Телефон") }
    .append(" ")
    .drawable(binding.tv, R.drawable.telephone)
    .append(" ")
    .append("нажмите")
    .append(" ")
    .bold { append("недавние") }
    .append(" ")
    .drawable(binding.tv, R.drawable.clock)

binding.tv.text = text

Upvotes: 6

Related Questions