Home > Software design >  Android Multiline text-only background
Android Multiline text-only background

Time:10-29

I want to implement a text view like this in my Android project:

enter image description here

The text can be multi-line and has a background, but the background must only cover the text and not the remaining empty area.

How can I achieve this?

CodePudding user response:

You can use a BackgroundColorSpan to set the background color from starting index to an end index of the TextView:

val textView = findViewById<TextView>(R.id.textView)
val spannable = SpannableString(textView.text.toString())
spannable.setSpan(
    BackgroundColorSpan(Color.parseColor("#C8ECFD")),
    0,
    spannable.length,
    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
textView.text = spannable

CodePudding user response:

It looks like your highlighting has rounded corners. If you do want the rounded corners, take a look at Drawing a rounded corner background on text, a Medium post by Florina Muntenescu.

That solution leaves some space between the lines while you example fills that space in, but I think that you can modify the code to fill it in.

  • Related