Make text (TextView) and Icon center in SpannableString

84 Views Asked by At

I've created a SpannableString with an icon in the middle. And it looks like this

enter image description here

As you can see here, the text is not aligned with the icon's center.

I've tried adding ImageSpan.ALIGN_BASELINE but it doesnt work. I've also tried gravity in Textview.

Here's my sample code:

fun showTextWithIcon(){
        val text = "Hey this is my text"
        val spannableString = SpannableString(text)

        val iconDrawable = ContextCompat.getDrawable(this,R.drawable.ic_icon)
        val iconSize = binding.textview.textSize.roundToInt()
        iconDrawable!!.setBounds(0, 0, iconDrawable.intrinsicHeight, iconDrawable.intrinsicWidth)
        val imageSpan = ImageSpan(iconDrawable)

        spannableString.setSpan(imageSpan, text.length /2, text.length/2+1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        binding.textview.text = spannableString
}
0

There are 0 best solutions below