Search code examples
javaandroidtextviewalignment

How to delete one word from a android textview (multiple lines) without affecting the alignment/position of other words


I have a android textview and I am setting 10 word sentence to it.

Now, I need to delete one word (say 4th word) without affecting the remaining word's positions/alignment.

Please refer below image. Also note, if am replacing that particular word with whitespaces, still alignment is slightly changing for remaining word's, as each character taking different width.

How can I achieve it using textview? Any help is much appreciated. Thanks.

expected output


Solution

  • You can use a SpannableString to apply the color of the background (looks like white in your picture) to the letters which should vanish.

    If you want to apply the effect to the fourth word ("sample") then you can write

    val startOfWord = 11
    val endOfWord = 16
    val spannable = SpannableString(“This is my sample text goes ...”)
    spannable.setSpan(ForegroundColorSpan(Color.WHITE), 
         startOfWord, endOfWord + 1, 
         Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    
    exampleTextView.text = spannable
    

    See also Spantastic text styling with Spans by Florina Muntenescu