2
votes

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

2

2 Answers

2
votes

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

0
votes

Here is an algorithm

  1. First: use StaticLayout.getDesiredWidth() for calculating the width of the word that you want to be hidden
  2. Second: use the same method to calculate the width of the space character.
  3. Third: get the no. of needed spaces by dividing the first on the second.

Let's code:

Note: I used the same text as you put.

<TextView
    android:id="@+id/textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="This is my sample text goes here\n with multiple words and lines and center aligned" />

Java

TextView textView = findViewById(R.id.textview);
String originalText = textView.getText().toString();
// Get the word that you want to replace
String text = originalText.substring(11, 18);
// Step 1: Get the word width
float wordWidth = StaticLayout.getDesiredWidth(text, new TextPaint());
// Step 2: Get the space width
float spaceWidth = StaticLayout.getDesiredWidth(" ", new TextPaint());
// Step 3: Get the needed no. of spaces
float nSpaces = wordWidth / spaceWidth;

// Step 4: Replace the word with the no. of spaces
StringBuilder newText = new StringBuilder(originalText.substring(0, 11));
for (int i = 0; i < nSpaces; i++) {
    newText.append(" ");
}

newText.append(originalText.substring(18));
textView.setText(newText);

Result

enter image description here